"use client";

import AuthButton from "@/components/auth/AuthButton";
import AuthHead from "@/components/auth/AuthHead";
import AuthInput from "@/components/auth/AuthInput";
import Container from "@/components/elements/Container";
import Link from "next/link";
import React, { useMemo, useState } from "react";
import useAxios from "@/hooks/useAxios";
import { useFormik } from "formik";
import * as yup from "yup";
import { useRouter } from "next/navigation";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";
import LocalePageShell from "@/components/i18n/LocalePageShell";

function ForgetPasswordPage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const { request, loading } = useAxios();
  const [destination, setDestination] = useState("");

  const schema = useMemo(
    () =>
      yup.object({
        identifier: yup
          .string()
          .required(t("auth.identifierRequired"))
          .test("identifier", t("auth.identifierInvalid"), (value) => {
            if (!value) return false;
            const trimmed = value.trim();
            return (
              /^(09\d{9})$/.test(trimmed) ||
              /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmed)
            );
          }),
      }),
    [t]
  );

  const formik = useFormik({
    initialValues: { identifier: "" },
    validationSchema: schema,
    onSubmit: async (values) => {
      try {
        const identifier = values.identifier.trim();
        const isMobile = /^09\d{9}$/.test(identifier);
        const response = (await request("POST", "/login/forgot_password", {
          identifier,
          ...(isMobile ? { mobile: identifier } : { email: identifier }),
        })) as {
          channel?: "sms" | "email";
          destination?: string;
          message?: string;
        };

        localStorage.setItem("reset_identifier", identifier);
        if (response.channel) {
          localStorage.setItem("reset_channel", response.channel);
        }
        if (response.destination) {
          setDestination(response.destination);
        }

        toast.success(response.message || t("auth.resetCodeSentDefault"));
        router.push("/change-passowrd");
      } catch (err: unknown) {
        const message =
          (err as { response?: { data?: { message?: string } } })?.response?.data
            ?.message || t("auth.sendCodeFailed");
        toast.error(message);
      }
    },
  });

  return (
    <LocalePageShell>
      <Container>
        <div className="p-4 flex flex-col items-center h-screen justify-center">
          <AuthHead title={t("auth.forgetPasswordTitle")} />
          <p className="text-sm text-gray-500 text-center mb-4 max-w-sm">
            {t("auth.forgetPasswordDesc")}
          </p>
          <form
            onSubmit={formik.handleSubmit}
            className="w-full max-w-sm flex flex-col items-center"
          >
            <AuthInput
              name="identifier"
              type="text"
              dir="ltr"
              placeholder={t("auth.identifierPlaceholder")}
              className={`border ${
                formik.touched.identifier && formik.errors.identifier
                  ? "border-red-500 dark:border-red-500"
                  : "border-gray-300"
              }`}
              value={formik.values.identifier}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
            />
            {formik.touched.identifier && formik.errors.identifier && (
              <small className="text-red-500 mt-2 block">
                {formik.errors.identifier}
              </small>
            )}
            {destination && (
              <small className="text-green-600 mt-2 block text-center">
                {t("auth.codeSentTo", { destination })}
              </small>
            )}
            <AuthButton
              type="submit"
              className="mt-5"
              loading={loading}
              disabled={loading}
            >
              {t("auth.sendResetCode")}
            </AuthButton>
          </form>
          <Link href="/login-with-username">
            <small className="text-[#667AC1] font-bold text-xs mt-8 block">
              {t("auth.backToLogin")}
            </small>
          </Link>
        </div>
      </Container>
    </LocalePageShell>
  );
}

export default ForgetPasswordPage;
