import React, { useState, useEffect } from "react";
import useNavigate from '@/hooks/useNavigate';
import { toast } from "react-toastify";
import { requestPasswordReset } from "@/services/authService";
import { assetPath } from "../../utils/assetPath";
import Link from "next/link";

export default function ForgotPassword() {
  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  // Add/remove body class for styling
  useEffect(() => {
    document.body.classList.add("loginbner");
    return () => {
      document.body.classList.remove("loginbner");
    };
  }, []);

  const submit = async (e) => {
    e.preventDefault();
    if (loading) return;

    if (!email) {
      toast.warn("Please enter your email");
      return;
    }

    setLoading(true);
    try {
      await requestPasswordReset(email.trim());
      toast.success("Password reset link sent to your email!");
      navigate("/auth/login");
    } catch (err) {
      console.error("Password reset failed:", err);
      const msg =
        err.response?.data?.message ||
        err.response?.data?.detail ||
        "Something went wrong";
      toast.error(msg);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="loginpnel">
      <form className="loginform" onSubmit={submit} autoComplete="off">
        <div className="loginlgo">
          <img src={assetPath("/assets/images/jury_intel_logo.png")} alt="logo" />
        </div>
        <div className="loginfrminr">
          <h3 className="mt-3 mb-2 fw-bold" style={{ color: "#0C3155" }}>
            Forgot Password?
          </h3>
          <div className="frmdata">
            <input
              type="email"
              placeholder="Enter your email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              disabled={loading}
            />
          </div>
          <div className="frmdatabtn">
            <input
              type="submit"
              value={loading ? "Sending..." : "Send Reset Link"}
              disabled={loading}
            />
          </div>
          <div className="frmdatalnks">
            <span>
              <Link href="/auth/login">Back to Login</Link>
            </span>
          </div>
        </div>
      </form>
    </div>
  );
}
