"use client";

import { useForm } from "react-hook-form";
import { toast } from "react-toastify";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { forgotPassword } from "@/store/slices/authSlice";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";

export default function ForgotPasswordForm() {
    const { register, handleSubmit: handleFormSubmit, formState: { errors } } = useForm();
    const dispatch = useAppDispatch();
    const { isLoading } = useAppSelector((state) => state.auth);
    const [isSent, setIsSent] = useState(false);
    const router = useRouter();


    const onSubmit = async (data: any) => {
        try {
            const resultAction = await dispatch(forgotPassword(data.email));
            if (forgotPassword.fulfilled.match(resultAction)) {
                toast.success("Reset link sent successfully");
                setIsSent(true);
                
                // For local development testing, redirect if backend provides the URL
                const payload = resultAction.payload as any;
                if (payload && payload.resetToken) {
                    router.push(`/reset-password?token=${payload.resetToken}`);
                }
            } else {
                toast.error((resultAction.payload as string) || "Failed to send reset link");
            }
        } catch (err: any) {
            toast.error(err.message || "An error occurred");
        }
    };

 
    return (
        <div className="flex flex-col flex-1 w-full lg:w-1/2">
            <div className="flex flex-col justify-center flex-1 w-full max-w-md mx-auto">
                <div>
                    <div className="mb-5 sm:mb-8">
                        <h1 className="mb-2 font-semibold text-gray-800 text-title-sm sm:text-title-md">
                            Forgot Password
                        </h1>
                    </div>
                    <div>
                        <form onSubmit={handleFormSubmit(onSubmit, (errors) => {
                            if (errors.email) toast.error(errors.email.message as string);
                            else toast.error("Please fill all required fields");
                        })}>
                            <div className="space-y-6">
                                <div>
                                    <label className="mb-1.5 block text-sm font-medium text-gray-700">Email 
                                        <span className="text-error-500">*</span> 
                                    </label>
                                    <div className="relative">
                                        <input 
                                            {...register("email", { 
                                                required: "Email is required",
                                                pattern: {
                                                    value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
                                                    message: "Invalid email address"
                                                }
                                            })}
                                            placeholder="Enter your email" 
                                            className={`h-11 w-full rounded-lg border appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none ${errors.email ? 'border-error-500' : 'border-gray-300'}`}
                                            type="text" 
                                            disabled={isSent || isLoading}
                                        />
                                    </div>
                                    {errors.email && <p className="mt-1 text-xs text-error-500">{errors.email.message as string}</p>}
                                </div>
                                <div>
                                    <button disabled={isSent || isLoading} className="inline-flex items-center justify-center font-medium gap-2 rounded-lg transition w-full px-4 py-3 text-sm bg-brand-950 text-white shadow-theme-xs hover:text-brand-950 hover:bg-yellow-500 disabled:bg-gray-400 disabled:opacity-50">
                                        {isLoading ? "Sending..." : isSent ? "Link Sent" : "Send Reset Link"}
                                    </button>
                                </div>
                            </div>
                            <div className="text-center mt-4">
                                <Link href="/login" className="text-sm text-brand-950 hover:text-yellow-500 underline">
                                    Back to Log In
                                </Link>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    );
}
