"use client";
import { createToken, setUserPermissions } from "@/actions/cookies";
import addToCart from "@/api/cart/addToCart";
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,
  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 useCart from "@/stores/cart";
import { useSettings } from "@/stores/settings";
import { zodResolver } from "@hookform/resolvers/zod";
import { useQueryClient } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import ReCAPTCHA from "react-google-recaptcha";
import { useForm } from "react-hook-form";
import { z } from "zod";

export default function SignIn() {
  const searchParams = useSearchParams();
  const phone = searchParams.get("phone")?.replace("+", "");
  const queryClient = useQueryClient();
  const [captcha, setCaptcha] = useState();
  const [captchaError, setCaptchaError] = useState(false);
  const [captchaState, setCaptchaState] = useState(0);
  const [resendTimer, setResendTimer] = useState(180); // 3 minutes in seconds
  const [canResend, setCanResend] = useState(false);
  const [isResending, setIsResending] = useState(false);
  const { settings } = useSettings();
  const t = useTranslations("sign-in");
  const label = useTranslations("form-labels");
  const error = useTranslations("form-errors");
  const router = useRouter();
  const { cart, clearCart, updateCart } = useCart();

  // 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]);

  useEffect(() => {
    setCaptchaState(settings?.site_settings?.captcha_enabled);
  }, [settings?.site_settings?.captcha_enabled]);

  const form = useForm({
    resolver: zodResolver(
      z.object({
        otp: z.string().min(6, t("otp-error")),
      })
    ),
  });
  const {
    formState: { isSubmitting },
  } = form;

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

  // Resend OTP function
  async function resendOTP() {
    setIsResending(true);

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

    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);
    }
  }

  async function onSubmit(values) {
    if (!captcha && captchaState == 1) {
      setCaptchaError(true); // Show error if captcha is not filled
      return; // Prevent form submission
    }
    const formData = new FormData();
    formData.append("phone", phone);
    formData.append("otp", values?.otp);
    const { data, error, message, code } = await postData({
      endPoint: "/user/verify_otp",
      body: formData,
    });
 
    if (error) {
      if (code === 400) {
        toastError(message);
      } else {
        toastError(t("error"));
      }
      return;
    }

    await Promise.all([
      createToken(data?.user?.token, data?.user?.refresh_token),
      setUserPermissions({
        is_affiliate: data?.user?.is_affiliate,
        is_vendor: data?.user?.is_vendor,
      }),
    ]);
    for (const item of cart) {
      await addToCart(item.id, item.quantity);
    }
    clearCart();
    toastSuccess(t("message"));
    router.replace("/");
    await queryClient.refetchQueries({
      queryKey: ["profile"],
    });
    setTimeout(() => {
      updateCart();
    }, 1000);
  }

  return (
    <>
      <CustomBreadcrumb />
      <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 mb-12">
            {t("verify-otp")}
          </h1>
          <div className="flex flex-row gap-2 justify-center flex-wrap">
            <Link href="/sign-in">
              <Button className="w-full">{t("title")}</Button>
            </Link>
          </div>
        </div>
        <Form {...form}>
          <form
            method="post"
            onSubmit={form.handleSubmit(onSubmit)}
            className="space-y-6 w-fit mx-auto"
          >
            <FormField
              dir="ltr"
              name="otp"
              control={form.control}
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-start">{t("enter-otp")}</FormLabel>
                  <div className="" 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>
              )}
            />

            {/* Resend OTP Section */}
            <div className="text-center space-y-2">
              {!canResend ? (
                <p className="text-sm text-gray-600">
                  {t("resend-timer") || "Resend OTP in"}:{" "}
                  {formatTime(resendTimer)}
                </p>
              ) : (
                <Button
                  type="button"
                  variant="ghost"
                  onClick={resendOTP}
                  disabled={isResending}
                  className="w-full"
                >
                  {isResending
                    ? t("sending") || "Sending..."
                    : t("resend-otp") || "Resend OTP"}
                </Button>
              )}
            </div>

            {/* RECAPTCHA */}
            {captchaState == 1 && (
              <ReCAPTCHA
                sitekey={process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY}
                onChange={(value) => {
                  setCaptcha(value);
                  setCaptchaError(false); // Clear error if captcha is filled
                }}
              />
            )}
            {captchaError && (
              <p className="text-red-500 text-sm">{error("captchaerror")}</p>
            )}
            {/* Submit button */}
            <SubmitButton text={t("confirm")} loading={isSubmitting} />
          </form>
        </Form>
      </section>
    </>
  );
}
