"use client";
import { yupResolver } from "@hookform/resolvers/yup";
import { useForm } from "react-hook-form";
import * as yup from "yup";
import { useLocale, useTranslations } from "next-intl";
import { ScrollArea } from "@/shared/ui/scroll-area";
import { Form } from "@/shared/ui/form";
import { AuthStage } from "@/interfaces/types";
import AppButton from "@/shared/buttons/AppButton";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/store/store";
import { useEffect, useState } from "react";
import ShowAlertMixin from "@/shared/ShowAlertMixin";
import { UseMutate } from "@/hooks/UseMutate";
import FormOtp from "@/shared/form-controls/FormOtp";
import { updateUser } from "@/store/auth.slice";

interface VerifyEmailFormProps {
  setAuthStage: (stage: AuthStage) => void;
  dialogOpen: (open: boolean) => void;
}
const VerifyEmailForm: React.FC<VerifyEmailFormProps> = ({
  setAuthStage,
  dialogOpen,
}) => {
  const [pinCodeValue, setPinCodeValue] = useState("");
  const locale = useLocale();
  const t = useTranslations("");
  const dispatch = useDispatch();
  const { storedValues } = useSelector(
    (state: RootState) => state.ForgetConfig,
  );
  const formSchema = yup.object({
    code: yup
      .string()
      .required(t("validations.code_required"))
      .length(
        4,
        t("validations.The code must be equal 4 numbers", { length: 4 }),
      ),
  });
  const form = useForm({
    resolver: yupResolver(formSchema),
    defaultValues: { code: "" },
  });

  const { mutate: VerifyMutate, isLoading: isLoadingVerify } = UseMutate({
    endpoint: "client/profile/confirm-email",
    onSuccess: (responseData: any) => {
      ShowAlertMixin({
        icon: "success",
        title: responseData?.message,
      });
      dispatch(updateUser({ email: storedValues?.email }));
      setTimeout(() => {
        setAuthStage("");
        dialogOpen(false);
      }, 200);
    },
  });
  const { mutate: ResendMutate, isLoading: isLoadingResend } = UseMutate({
    endpoint: "client/profile/resend-code",
    onSuccess: (responseData: any) => {
      ShowAlertMixin({
        icon: "success",
        title: responseData?.message,
      });
    },
  });
  async function onSubmit(values: yup.InferType<typeof formSchema>) {
    const finalOut = {
      code: pinCodeValue,
      token: storedValues?.verification_token,
    };
    await VerifyMutate({ ...finalOut });
  }

  // Resend Code
  const handleSendTime = async () => {
    await ResendMutate({
      token: storedValues?.verification_token,
    });
  };
  useEffect(() => {
    if (!storedValues?.verification_token) {
      setAuthStage("");
      dialogOpen(false);
    }
  }, [storedValues?.verification_token]);

  return (
    <ScrollArea className="grow " dir={locale === "en" ? "ltr" : "rtl"}>
      <div className="h-[350px] flex flex-col pe-2 py-2">
        <div className="text-center mb-2">
          <div className="w-16 h-16 bg-primary-light rounded-full flex items-center justify-center mx-auto mb-4">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="32"
              height="32"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
              className="lucide lucide-mail *:stroke-primary"
            >
              <rect width="20" height="16" x="2" y="4" rx="2"></rect>
              <path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"></path>
            </svg>
          </div>
          <h2 className="text-2xl mb-2">تأكيد الحساب</h2>
          <p className="text-text-secondary">
            {t("Text.verify_code_email", { email: storedValues?.email })}
          </p>
        </div>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)}>
            <div className="flex flex-col gap-4">
              <FormOtp
                pinCodeValue={pinCodeValue}
                setPinCodeValue={setPinCodeValue}
                name="code"
                length={4}
                handleSendTime={handleSendTime}
              />

              <div className="!pt-2 w-full h-max ">
                <AppButton
                  title={t("BUTTONS.confirm")}
                  buttonType="submit"
                  button
                  loader={isLoadingVerify}
                  disabled={isLoadingVerify || isLoadingResend}
                  className="!w-full  !h-[56px] !rounded-xl "
                />
              </div>
            </div>
          </form>
        </Form>
      </div>
    </ScrollArea>
  );
};

export default VerifyEmailForm;
