"use client";

import React from "react";
import { Formik, Form } from "formik";
import Input from "@/components/ui/Input";
import Button from "@/components/ui/Button";
import { cn, maskEmail } from "@/lib/helpers";
import { useTranslation } from "react-i18next";
import { OTP_LENGTH } from "./otpInput";
import { useEmailVerification } from "./useEmailVerification";
import type { OtpType } from "@/features/auth/services/authApi";

export interface EmailVerificationFormProps {
  email?: string;
  /* `register` or `password` — `verify_otp_or_token` and
     `resend_otp_or_token` both validate it with `Rule::in`. */
  otp_type?: OtpType;
  onClose?: () => void;
  onShowLogin?: () => void;
  onShowResetPassword?: (email: string, token: string) => void;
  isModal?: boolean;
}

export default function EmailVerificationForm({
  email = "",
  otp_type = "register",
  onClose,
  onShowLogin,
  onShowResetPassword,
  isModal,
}: EmailVerificationFormProps) {
  const { t } = useTranslation();
  const {
    verifyEmailMutation,
    resendOtpMutation,
    timer,
    isResendDisabled,
    otpError,
    otpRefs,
    initialValues,
    handleOtpChange,
    handleOtpPaste,
    handleBackspace,
    handleSubmit,
    resendOtp,
  } = useEmailVerification({
    email,
    otp_type,
    onClose,
    onShowLogin,
    onShowResetPassword,
  });

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

  const isLoading = verifyEmailMutation.isPending;
  const isResendLoading = resendOtpMutation.isPending;

  return (
    <div className={cn(!onClose && "border-t", "border-[#000]")}>
      <div
        className={`${isModal ? "" : "2xl:py-[40px] laptopmain:py-[50px] laptop:py-[40px] lg:py-[40px] py-[40px]"}`}
      >
        <h2 className="2xl:pb-11 lg:pb-5 pb-5 text-center font-bold xs:text-[22px] xs:leading-[26px] text-[28px] leading-[48px] md:text-[32px] md:leading-[52px] lg:text-[30px] lg:leading-[60px] 2xl:text-[50px] xl:leading-[68.09px] tracking-[0px] text-[#29246D]">
          {isModal ? t("COMMON.ENTER.OTP") : t("COMMON.EMAIL_VERIFICATION")}
        </h2>

        <Formik initialValues={initialValues} onSubmit={handleSubmit}>
          {({ setFieldValue, values, resetForm }) => (
            <div className="flex justify-center">
              <div className="w-[90%] 2xl:w-[658px] lg:w-[658px] md:w-[90%] rounded-lg bg-white">
                <Form>
                  <div className="flex gap-3 justify-center" dir="ltr">
                    {[...Array(OTP_LENGTH)].map((_, index) => (
                      <Input
                        key={index}
                        name={`otp${index + 1}`}
                        type="text"
                        maxLength={1}
                        dir="ltr"
                        ref={(el) => {
                          otpRefs.current[index] = el;
                        }}
                        onChange={(e) =>
                          handleOtpChange(e, index, values, setFieldValue)
                        }
                        onKeyDown={(e) =>
                          handleBackspace(e, index, setFieldValue)
                        }
                        onPaste={(e) => handleOtpPaste(e, index, setFieldValue)}
                        hideError
                        customClass="w-[50px] h-[40px] text-center text-xl"
                        className="text-center p-0"
                      />
                    ))}
                  </div>

                  {otpError && (
                    <div className="text-red-500 text-sm mt-2 text-center">
                      {otpError}
                    </div>
                  )}

                  <Button
                    className="mx-auto mt-[25px] w-[400px] mobilescreen:w-[200px]"
                    variant="primary"
                    size="medium"
                    type="submit"
                    disabled={isLoading}
                    loading={isLoading}
                  >
                    {t("COMMON.SUBMIT")}
                  </Button>

                  <p className="text-center pt-8 text-secondary-100 text-xl">
                    {formatTime(timer)}
                  </p>
                  {/* A real <button>: resending the code is the only way past a
                      lost OTP, and it was a mouse-only <p>. `disabled` now
                      carries the state the opacity class was only showing. */}
                  <button
                    type="button"
                    disabled={isResendDisabled || isResendLoading}
                    className={`w-full text-center pt-1 text-[#29246D80] text-xl cursor-pointer ${isResendDisabled || isResendLoading ? "opacity-50 cursor-not-allowed" : ""}`}
                    onClick={() => { void resendOtp(resetForm); }}
                  >
                    {isResendLoading
                      ? t("COMMON.SENDING_CODE")
                      : t("COMMON.RESEND_CODE")}
                  </button>
                </Form>
                <p className="pl-3 text-primary-5 extrasmall:text-base text-center text-[20px] pt-[30px]">
                  {t("COMMON.OTP_SENT")}
                  <span className="pl-3 text-primary-5">
                    {maskEmail(email)}
                  </span>
                </p>
              </div>
            </div>
          )}
        </Formik>
      </div>
    </div>
  );
}
