"use client";

import postData from "@/api/post-data";
import CustomBreadcrumb from "@/app/ui/shared/CustomBreadcrumb";
import SubmitButton from "@/app/ui/shared/SubmitButton";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import {
  InputOTP,
  InputOTPGroup,
  InputOTPSeparator,
  InputOTPSlot,
} from "@/components/ui/input-otp";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { zodResolver } from "@hookform/resolvers/zod";
import clsx from "clsx";
import { useLocale, useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { useEffect, useState, useTransition } from "react";
import { useForm } from "react-hook-form";
import { FaSpinner } from "react-icons/fa6";
import { z } from "zod";

export default function VerifyCode({ params: { email: emailEncoded } }) {
  const t = useTranslations("verify-code");
  const [isResending, setIsResending] = useState(false);
  const [resendTimer, setResendTimer] = useState(180); // 3 minutes in seconds
  const error = useTranslations("form-errors");
  const router = useRouter();
  const locale = useLocale();
  const [canResend, setCanResend] = useState(false);
  const s = useTranslations("sign-in");

  const formatTime = (seconds) => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`;
  };

  // Timer effect
  useEffect(() => {
    if (resendTimer > 0) {
      const interval = setInterval(() => {
        setResendTimer((prev) => {
          if (prev <= 1) {
            setCanResend(true);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);

      return () => clearInterval(interval);
    }
  }, [resendTimer]);
  async function resendOTP() {
    setIsResending(true);

    const formData = new FormData();
    formData.append("phone", emailEncoded);

    try {
      const { data, error, message, code } = await postData({
        endPoint: "/reset/check_email", // Adjust this endpoint as needed
        body: formData,
      });

      if (error) {
        if (code === 400) {
          toastError(message);
        } else {
          toastError("Failed to resend OTP");
        }
      } else {
        toastSuccess("OTP sent successfully");
        // Reset timer and disable resend button
        setResendTimer(180);
        setCanResend(false);
      }
    } catch (err) {
      toastError(t("resend-error") || "Failed to resend OTP");
    } finally {
      setIsResending(false);
    }
  }

  const form = useForm({
    resolver: zodResolver(
      z.object({
        pin_code: z
          .string({ message: error("required") })
          .length(6, { message: error("pin") }),
      })
    ),
  });
  const {
    formState: { isSubmitting },
  } = form;

  async function onSubmit(data) {
    const formData = new FormData();
    formData.append("phone", emailEncoded);
    formData.append("pin_code", data.pin_code);
    const { error, message } = await postData({
      endPoint: "/reset/check_code",
      body: formData,
      locale,
    });
    if (error) {
      toastError(message);
      return;
    }

    router.push("/forgot-password/new-password/" + data.pin_code);
  }

  return (
    <>
      <CustomBreadcrumb subs={true} />
      <section className="max-md:mx-4 mt-12 mb-20 rounded-lg p-4 md:p-8 shadow-lg md:w-1/2 mx-auto">
        <div className="space-y-2 mb-12">
          <h1 className="font-bold text-xl text-center md:text-2xl lg:text-3xl text-dark">
            {t("title")}
          </h1>
          <p className="text-sm mb-12 text-center">{t("message")}</p>
        </div>
        <Form {...form}>
          <form
            method="post"
            onSubmit={form.handleSubmit(onSubmit)}
            className="space-y-6"
          >
            <FormField
              name="pin_code"
              control={form.control}
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-start">{t("enter-otp")}</FormLabel>
                  <div className=" w-fit text-center" dir="ltr">
                    <FormControl dir="ltr">
                      <InputOTP maxLength={6} {...field} dir="ltr">
                        <InputOTPGroup dir="ltr">
                          <InputOTPSlot index={0} />
                          <InputOTPSlot index={1} />
                        </InputOTPGroup>
                        <InputOTPGroup dir="ltr">
                          <InputOTPSlot index={2} />
                          <InputOTPSlot index={3} />
                        </InputOTPGroup>
                        <InputOTPGroup dir="ltr">
                          <InputOTPSlot index={4} />
                          <InputOTPSlot index={5} />
                        </InputOTPGroup>
                      </InputOTP>
                    </FormControl>
                  </div>

                  <FormMessage />
                </FormItem>
              )}
            />
            <SubmitButton text={t("verify-code")} loading={isSubmitting} />
            {/* Resend code */}
            <FormDescription>
              {/* Resend OTP Section */}
              <div className="text-center space-y-2">
                {!canResend ? (
                  <p className="text-sm text-gray-600">
                    {s("resend-timer") || "Resend OTP in"}:{" "}
                    {formatTime(resendTimer)}
                  </p>
                ) : (
                  <Button
                    type="button"
                    variant="ghost"
                    onClick={resendOTP}
                    disabled={isResending}
                    className="w-full"
                  >
                    {isResending
                      ? s("sending") || "Sending..."
                      : s("resend-otp") || "Resend OTP"}
                  </Button>
                )}
              </div>
            </FormDescription>
          </form>
        </Form>
      </section>
    </>
  );
}
