"use client";

import React from "react";

import { Formik, Form, FormikHelpers } from "formik";
import * as Yup from "yup";
import Input from "@/components/ui/Input";
import Button from "@/components/ui/Button";
import { useMutation } from "@tanstack/react-query";
import { forgotPasswordRequest } from "@/features/auth/services/authApi";
import { YupEmail } from "@/features/shared/schemas";
import { toast } from "sonner";
import { useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/helpers";
import { useLanguageStore } from "@/store/languageStore";
import {
  getApiFieldErrors,
  getLocalizedApiMessage,
} from "@/lib/api/errors";
import type { OtpType } from "@/features/auth/services/authApi";
import { splitFormApiErrors } from "@/features/shared/splitFormApiErrors";

export interface ForgotPasswordFormProps {
  onClose?: () => void;
  onShowEmailVerification?: (email: string, otp_type: OtpType) => void;
  isModal?: boolean;
}

export default function ForgotPasswordForm({
  onShowEmailVerification,
  onClose,
  isModal,
}: ForgotPasswordFormProps) {
  const { t } = useTranslation();
  const router = useRouter();
  const selectedLanguage = useLanguageStore((s) => s.language);

  const forgotPasswordMutation = useMutation({
    mutationFn: forgotPasswordRequest,
  });

  const initialValues = {
    email: "",
  };

  const validationSchema = Yup.object({
    email: YupEmail,
  });

  const handleSubmit = async (
    values: typeof initialValues,
    { resetForm, setFieldError }: FormikHelpers<typeof initialValues>,
  ) => {
    try {
      const response = await forgotPasswordMutation.mutateAsync(values);
      toast.success(response?.msg || t("COMMON.TOAST.EMAIL_SENT_SUCCESSFULLY"));
      resetForm();
      if (onShowEmailVerification) {
        onShowEmailVerification(values.email || "", "password");
        onClose?.();
      } else {
        router.push(
          `/email-verification?email=${encodeURIComponent(values.email)}&otp_type=password`,
        );
      }
    } catch (error) {
      /*
       * `non_field_errors` arrives as `{ en, ar }`, as a `string[]`, or as a
       * bare string depending on the endpoint revision, and this used to test
       * all three by hand. `getApiFieldErrors` already normalises every one of
       * them to a single string per field.
       *
       * Detection stays pinned to **English**: the phrase being matched is
       * English, so reading the Arabic message would never match it. The
       * message shown to the user is still taken in the active language below.
       *
       * This is a text match on a server message and therefore fragile — the
       * same fragility `useLoginForm` documents, where the API's wording has
       * already drifted once. The structured `action` field is the signal to
       * prefer if this endpoint ever grows one.
       */
      const isNotActive = (
        getApiFieldErrors(error, "en").non_field_errors ?? ""
      ).includes("is not active");

      if (isNotActive) {
        toast.error(t("COMMON.TOAST.USER_NOT_ACTIVE"));
        if (onClose && onShowEmailVerification) {
          onClose();
          onShowEmailVerification(values.email || "", "register");
        } else {
          router.push(
            `/email-verification?email=${encodeURIComponent(values.email)}&otp_type=register`,
          );
        }
      } else {
        // An `email` field error sits under the field (PDF p.37); the rest is toasted.
        const { mapped, rest } = splitFormApiErrors(error, selectedLanguage, ["email"], setFieldError);
        if (rest.length > 0) {
          rest.forEach((message) => toast.error(message));
        } else if (mapped === 0) {
          toast.error(
            getLocalizedApiMessage(
              error,
              selectedLanguage,
              t("COMMON.TOAST.EMAIL_SEND_FAILED"),
            ),
          );
        }
      }
    }
  };

  const isLoading = forgotPasswordMutation.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]"}`}
      >
        {!isModal && (
          <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]">
            {t("COMMON.FORGOT_PASSWORD")}
          </h2>
        )}

        <Formik
          initialValues={initialValues}
          validationSchema={validationSchema}
          onSubmit={handleSubmit}
        >
          {() => (
            <div className="flex justify-center">
              <div className="w-[90%] 2xl:w-[658px] lg:w-[658px] md:w-[90%] rounded-lg bg-white">
                <Form>
                  <Input
                    name="email"
                    type="email"
                    label={t("COMMON.ENTER_EMAIL")}
                  />

                  <Button
                    className="mx-auto mt-[25px]"
                    variant="primary"
                    size="medium"
                    type="submit"
                    disabled={isLoading}
                  >
                    {t("COMMON.SEND")}
                  </Button>
                </Form>
                <p dir={selectedLanguage === "ar" ? "rtl" : "ltr"} className="text-primary-5 text-center extrasmall:text-base font-[400] text-[20px] leading-[27.24px] pt-7">
                  {t("COMMON.FORGOT_PASSWORD_INSTRUCTION")}
                </p>
              </div>
            </div>
          )}
        </Formik>
      </div>
    </div>
  );
}
