"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import AuthCard from "./AuthCard";
import { MailIcon } from "./icons";
import { useAppDispatch, useAppSelector } from "@/state/hooks";
import { forgotPasswordAdmin } from "@/state/auth";

type ForgotFormValues = {
  email: string;
};

export default function ForgotPasswordScreen() {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const { forgotStatus, error: reduxError } = useAppSelector((state) => state.auth);

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<ForgotFormValues>();

  const onSubmit = async (data: ForgotFormValues) => {
    try {
      const resultAction = await dispatch(forgotPasswordAdmin(data.email));

      if (forgotPasswordAdmin.fulfilled.match(resultAction)) {
        toast.success(resultAction.payload.message || "Verification code sent to your email");
        router.push(`/verify-email?email=${encodeURIComponent(data.email)}`);
      } else if (forgotPasswordAdmin.rejected.match(resultAction)) {
        const errorMsg =
          (resultAction.payload as { message?: string })?.message ||
          "Failed to send verification code";
        toast.error(errorMsg);
      }
    } catch (err: unknown) {
      toast.error((err as Error)?.message || "Failed to send verification code");
    }
  };

  const loading = forgotStatus === "loading";

  return (
    <AuthCard
      title="Forgot Your Password?"
      subtitle="Enter your registered email to reset your password."
      footer={
        <>
          Remember password?{" "}
          <Link href="/login" className="font-medium text-[#1D4ED8] hover:underline">
            Log in
          </Link>
        </>
      }
    >
      <form
        method="post"
        action="#"
        onSubmit={(e) => {
          e.preventDefault();
          handleSubmit(onSubmit)(e);
        }}
      >
        <div className="min-h-[220px]">
          <div>
            <label className="mb-1.5 block text-[14px] font-medium leading-[22px] tracking-[0.01em] text-[#4E616A]">Email</label>
            <div
              className={`flex h-[54px] items-center gap-2 rounded-lg border bg-white px-4 focus-within:border-[#1657D9] ${
                errors.email ? "border-red-500" : "border-[#D0D5DD]"
              }`}
            >
              <MailIcon />
              <input
                type="email"
                placeholder="example@email.com"
                className="min-w-0 flex-1 border-0 bg-transparent text-[13px] text-[#101828] outline-none placeholder:text-[#98A2B3]"
                {...register("email", {
                  required: "Email is required",
                  pattern: {
                    value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
                    message: "Invalid email address",
                  },
                })}
              />
            </div>
            {errors.email && <p className="mt-1 text-[11px] text-red-500">{errors.email.message}</p>}
          </div>

          {reduxError && (
            <p className="mt-3 text-[12px] font-medium text-red-600 bg-red-50 p-2.5 rounded-lg border border-red-200">
              {reduxError}
            </p>
          )}
        </div>

        <button
          type="submit"
          disabled={loading}
          className="mt-8 h-10 w-full rounded-lg bg-[#1D4ED8] text-[14px] font-medium text-white transition-colors hover:bg-[#1E40AF] disabled:opacity-60 cursor-pointer"
        >
          {loading ? "Sending..." : "Send Verification Code"}
        </button>
      </form>
    </AuthCard>
  );
}
