"use client";

import { FiMail, FiLock } from "react-icons/fi";
import Input from "../../ui/CustomInput";
import Button from "../../ui/Button";
import { useModal } from "../../../lib/modal-system/ModalContext";
import {
  forgotPasswordSchema,
  ForgotPasswordSchema,
} from "../../../hooks/features/auth/forgot-password/schema";
import { useAppForm } from "../../../hooks/useAppForm";
import useForgotPassword from "../../../hooks/features/auth/forgot-password/useForgotPassword";

export default function ForgotPasswordForm() {
  const { openModal } = useModal();

  const { handleForgotPassword, loading } = useForgotPassword();

  const { register, reset, errors, handleSubmit } =
    useAppForm<ForgotPasswordSchema>({
      schema: forgotPasswordSchema,
      defaultValues: {
        email: "",
      },
      onSubmit: async (data) => {
        try {
          await handleForgotPassword(data);

          openModal("CHECK_EMAIL_FOR_PASSWORD_RESET", {
            email: data.email,
          });
          reset();
        } catch (error) {}
      },
    });

  return (
    <>
      <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-full border border-[#E5D8FF] text-link-1 md:h-16 md:w-16">
        <FiLock size={24} />
      </div>

      <h2 className="mt-7 text-center font-heading text-xl font-semibold text-heading">
        Forgot password?
      </h2>

      <p className="mx-auto mt-4 max-w-117 text-center font-body text-base leading-7 text-text">
        Enter the email address linked to your account. We'll send you a
        password reset link.
      </p>

      <div className="mt-6">
        <label className="mb-2 block font-body text-sm font-medium text-heading">
          Email<span className="text-danger">*</span>
        </label>

        <Input
          register={register("email")}
          error={errors.email?.message}
          icon={<FiMail />}
          placeholder="Enter Your Email"
        />
      </div>

      <Button loading={loading} className="mt-6 w-full" onClick={handleSubmit}>
        Send Reset Link
      </Button>

      <div className="mt-6 text-center">
        <button
          type="button"
          onClick={() => openModal("LOGIN", {})}
          className="font-body text-sm font-medium text-link-1 cursor-pointer"
        >
          Back to Login
        </button>
      </div>
    </>
  );
}
