"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, { 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";

const schema = yup.object({
  identifier: yup
    .string()
    .required("ایمیل یا شماره موبایل الزامی است")
    .test("identifier", "ایمیل یا شماره موبایل معتبر نیست", (value) => {
      if (!value) return false;
      const trimmed = value.trim();
      return (
        /^(09\d{9})$/.test(trimmed) ||
        /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmed)
      );
    }),
});

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

  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 || "کد بازیابی ارسال شد");
        router.push("/change-passowrd");
      } catch (err: unknown) {
        const message =
          (err as { response?: { data?: { message?: string } } })?.response?.data
            ?.message || "ارسال کد ناموفق بود";
        toast.error(message);
      }
    },
  });

  return (
    <Container>
      <div className="p-4 flex flex-col items-center h-screen justify-center">
        <AuthHead title="فراموشی کلمه عبور" />
        <p className="text-sm text-gray-500 text-center mb-4 max-w-sm">
          ایمیل (برای حساب گوگل) یا شماره موبایل خود را وارد کنید تا کد بازیابی
          ارسال شود.
        </p>
        <form
          onSubmit={formik.handleSubmit}
          className="w-full max-w-sm flex flex-col items-center"
        >
          <AuthInput
            name="identifier"
            type="text"
            dir="ltr"
            placeholder="email@example.com یا 09xxxxxxxxx"
            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">
              کد به {destination} ارسال شد
            </small>
          )}
          <AuthButton
            type="submit"
            className="mt-5"
            loading={loading}
            disabled={loading}
          >
            ارسال کد بازیابی
          </AuthButton>
        </form>
        <Link href="/login-with-username">
          <small className="text-[#667AC1] font-bold text-xs mt-8 block">
            بازگشت به ورود
          </small>
        </Link>
      </div>
    </Container>
  );
}

export default ForgetPasswordPage;
