"use client";

import {
  useState,
  useEffect,
  useRef,
  ChangeEvent,
  KeyboardEvent,
  ClipboardEvent,
} from "react";
import { FormikHelpers } from "formik";
import { useRouter } from "next/navigation";
import { useMutation } from "@tanstack/react-query";
import { emailVerificationRequest, resendOtpRequest } from "@/features/auth/services/authApi";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { useLanguageStore } from "@/store/languageStore";
import {
  buildOtpString,
  digitsOnly,
  EMPTY_OTP,
  isOtpComplete,
  nextFocusIndex,
  OTP_LENGTH,
  parsePastedOtp,
  type OtpValues,
} from "./otpInput";
import { type EmailVerificationFormProps } from "./EmailVerificationForm";
import {
  getApiErrorMessages,
  getApiFieldErrors,
  getLocalizedApiMessage,
} from "@/lib/api/errors";

/**
 * The verification screen's behaviour: the resend cooldown, the six boxes'
 * keyboard handling and the verify/resend calls.
 *
 * The box rules themselves are pure and live in `otpInput.ts`.
 */
export function useEmailVerification({
  email = "",
  otp_type = "register",
  onClose,
  onShowLogin,
  onShowResetPassword,
}: EmailVerificationFormProps) {
  const router = useRouter();
  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);

  const verifyEmailMutation = useMutation({
    mutationFn: emailVerificationRequest,
  });

  const resendOtpMutation = useMutation({
    mutationFn: resendOtpRequest,
  });

  // Resend cooldown is capped at 1 minute regardless of the configured value.
  const initialTimer = Math.min(Number(process.env.NEXT_PUBLIC_OTP_TIMER) || 1800, 60);
  const [timer, setTimer] = useState(initialTimer);
  /*
   * Derived, not stored: the flag was only ever `true` while the countdown
   * ran. It started `true`, was set `false` when the timer reached zero, and
   * was set back to `true` alongside `setTimer(initialTimer)` on resend — i.e.
   * it tracked `timer > 0` exactly. Storing it meant the "Resend" link stayed
   * disabled for one extra commit after the countdown ended.
   *
   * `initialTimer` is clamped to at least 1 above, so the initial value is
   * still `true`.
   */
  const isResendDisabled = timer > 0;
  const [otpError, setOtpError] = useState<string | null>(null);

  const otpRefs = useRef<Array<HTMLInputElement | null>>(
    Array(OTP_LENGTH).fill(null)
  );

  useEffect(() => {
    let interval: ReturnType<typeof setInterval>;
    if (timer > 0) {
      interval = setInterval(() => {
        setTimer((prev) => prev - 1);
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [timer]);

  const initialValues: OtpValues = EMPTY_OTP;

  const handleOtpChange = (
    e: ChangeEvent<HTMLInputElement>,
    index: number,
    values: OtpValues,
    setFieldValue: (
      field: string,
      value: unknown,
      shouldValidate?: boolean
    ) => void
  ) => {
    const value = digitsOnly(e.target.value);
    setFieldValue(`otp${index + 1}`, value);

    if (value && index < OTP_LENGTH - 1) {
      otpRefs.current[index + 1]?.focus();
    }

    const complete = isOtpComplete({
      ...values,
      [`otp${index + 1}`]: value,
    });
    setOtpError(complete ? null : t("COMMON.PLEASE_ENTER_ALL_6_OTP_DIGITS"));
  };

  const handleOtpPaste = (
    e: ClipboardEvent<HTMLInputElement>,
    index: number,
    setFieldValue: (
      field: string,
      value: unknown,
      shouldValidate?: boolean
    ) => void
  ) => {
    e.preventDefault();
    const digits = parsePastedOtp(e.clipboardData.getData("text"));

    if (digits.length > 0) {
      digits.forEach((digit, i) => {
        setFieldValue(`otp${i + 1}`, digit);
      });

      otpRefs.current[nextFocusIndex(index, digits.length)]?.focus();

      setOtpError(
        digits.length === OTP_LENGTH
          ? null
          : t("COMMON.PLEASE_ENTER_ALL_6_OTP_DIGITS")
      );
    }
  };

  const handleBackspace = (
    e: KeyboardEvent<HTMLInputElement>,
    index: number,
    setFieldValue: (field: string, value: unknown) => void
  ) => {
    if (
      e.key === "Backspace" &&
      !(e.target as HTMLInputElement).value &&
      index > 0
    ) {
      setFieldValue(`otp${index + 1}`, "");
      otpRefs.current[index - 1]?.focus();
    }
  };

  const handleSubmit = async (
    values: OtpValues,
    { resetForm }: FormikHelpers<OtpValues>
  ) => {
    try {
      if (!isOtpComplete(values)) {
        setOtpError(t("COMMON.ENTER_OTP"));
        return;
      }

      const otp = buildOtpString(values);
      const response = await verifyEmailMutation.mutateAsync({
        otp,
        type: otp_type,
        email,
      });

      toast.success(t("COMMON.TOAST.EMAIL_VERIFIED_SUCCESSFULLY"));
      resetForm();
      setOtpError(null);
      onClose?.();

      if (otp_type === "register") {
        if (onShowLogin) {
          onShowLogin();
        } else {
          router.push("/login");
        }
      } else if (otp_type === "password") {
        if (onShowResetPassword) {
          onShowResetPassword(email, response.data.token);
        } else {
          router.push(`/reset-password?email=${encodeURIComponent(email)}&token=${encodeURIComponent(response.data.token)}`);
        }
      }
    } catch (error) {
      /*
       * BE-164 (backend `0572fb7`) — an organization still awaiting approval
       * (or rejected) is **activated** but gets login's 403 instead of a
       * token, with the reason under `organization_status`. The code was
       * right, so this is the success path: say so, plus the approval state,
       * and go to sign-in (which will answer the same until an admin approves).
       */
      const approval = getApiFieldErrors(error, selectedLanguage).organization_status;
      if (otp_type === "register" && approval) {
        toast.success(t("COMMON.TOAST.EMAIL_VERIFIED_SUCCESSFULLY"));
        toast.info(approval);
        resetForm();
        setOtpError(null);
        onClose?.();
        if (onShowLogin) {
          onShowLogin();
        } else {
          router.push("/login");
        }
        return;
      }
      /* `lib/api/errors.ts` covers both envelope shapes; this walked
         the legacy `errors[field][lang]` map by hand. */
      const messages = getApiErrorMessages(error, selectedLanguage);
      if (messages.length > 0) {
        messages.forEach((message) => toast.error(message));
      } else {
        toast.error(getLocalizedApiMessage(error, selectedLanguage, t("COMMON.TOAST.EMAIL_VERIFICATION_FAILED")));
      }
    }
  };

  const resendOtp = async (resetForm: FormikHelpers<OtpValues>["resetForm"]) => {
    try {
      if (isResendDisabled || resendOtpMutation.isPending) return;
      resetForm();
      setOtpError(null);
      otpRefs.current[0]?.focus();
      const response = await resendOtpMutation.mutateAsync({
        email,
        type: otp_type,
      });
      toast.success(response?.msg || t("COMMON.TOAST.OTP_RESENT_SUCCESSFULLY"));
      setTimer(initialTimer);
    } catch (error) {
      /* `lib/api/errors.ts` covers both envelope shapes; this walked
         the legacy `errors[field][lang]` map by hand. */
      const messages = getApiErrorMessages(error, selectedLanguage);
      if (messages.length > 0) {
        messages.forEach((message) => toast.error(message));
      } else {
        toast.error(getLocalizedApiMessage(error, selectedLanguage, t("COMMON.TOAST.OTP_RESENT_FAILED")));
      }
    }
  };
  return {
    router,
    selectedLanguage,
    verifyEmailMutation,
    resendOtpMutation,
    initialTimer,
    timer,
    setTimer,
    isResendDisabled,
    otpError,
    setOtpError,
    otpRefs,
    initialValues,
    handleOtpChange,
    handleOtpPaste,
    handleBackspace,
    handleSubmit,
    resendOtp,
  };
}
