"use client";
import { createToken, setUserPermissions } from "@/actions/cookies";
import addToCart from "@/api/cart/addToCart";
import postData from "@/api/post-data";
import PasswordInput from "@/app/ui/form/PassowrdInput";
import CustomBreadcrumb from "@/app/ui/shared/CustomBreadcrumb";
import CustomPhoneInput from "@/app/ui/shared/CustomPhoneInput";
import SubmitButton from "@/app/ui/shared/SubmitButton";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
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 } 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 queryClient = useQueryClient();
  const [captcha, setCaptcha] = useState();
  const [captchaError, setCaptchaError] = useState(false);
  const [captchaState, setCaptchaState] = useState(0);
  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();

  useEffect(() => {
    setCaptchaState(settings?.site_settings?.captcha_enabled);
  }, [settings?.site_settings?.captcha_enabled]);
  const form = useForm({
    resolver: zodResolver(
      z.object({
        phone: z.string({ errorMap: () => ({ message: error("phone") }) }),
        password: z
          .string({ message: error("required") })
          .min(6, { message: error("min6") })
          .max({ message: error("max64") }),
        remember_me: z.boolean().optional(),
      })
    ),
  });
  const {
    formState: { isSubmitting },
  } = form;

  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("is_vendor", "0");
    formData.append("phone", values.phone.replace("+", ""));
    formData.append("password", values.password);
    const { data, error, message, code } = await postData({
      endPoint: "/user/login",
      body: formData,
    });
    if (error) {
      if (Array.isArray(data)) {
        router.push(`/verify-otp?phone=${values.phone.replace("+", "")}`);
        return;
      }
      if (code === 401) {
        toastError(message);
      } else {
        toastError(message, data?.phone[0]);
      }
      return;
    }

    await Promise.all([
      createToken(data.token, data.refresh_token),
      setUserPermissions({
        is_affiliate: data?.is_affiliate,
        is_vendor: data?.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("title")}
          </h1>
          <div className="flex flex-row gap-2 justify-center flex-wrap">
            <Link href="/sign-up">
              <Button className="w-full">{t("create-account")}</Button>
            </Link>
          </div>
        </div>
        <Form {...form}>
          <form
            method="post"
            onSubmit={form.handleSubmit(onSubmit)}
            className="space-y-6"
          >
            {/* <FormField
              name="email"
              control={form.control}
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <Input {...field} placeholder={label("email")} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            /> */}

            <FormField
              name="phone"
              control={form.control}
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <CustomPhoneInput
                      value={field.value}
                      valueOnChange={field.onChange}
                      placeholder={label("mobile")}
                      className={"flex gap-2"}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              name="password"
              control={form.control}
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <PasswordInput
                      field={field}
                      placeholder={label("password")}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <div className="flex justify-between items-end">
              <FormField
                name="remember_me"
                control={form.control}
                render={({ field }) => (
                  <FormItem className="flex items-end gap-2">
                    <FormLabel>{label("remember-me")}</FormLabel>
                    <FormControl>
                      <Checkbox
                        checked={field.value}
                        onCheckedChange={field.onChange}
                        className="border-btnColor text-btnColor"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <Link href="/forgot-password" className="text-main underline">
                {t("forgot-password")}
              </Link>
            </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("title")} loading={isSubmitting} />
          </form>
        </Form>
      </section>
    </>
  );
}
