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

export default function Login() {
  const { refreshProfile } = useProfile();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  //  Add this effect to manage the body class
  useEffect(() => {
    document.body.classList.add("loginbner");
    return () => {
      document.body.classList.remove("loginbner");
    };
  }, []);

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

    if (!email || !password) {
      toast.warn("Please enter email and password");
      return;
    }

    setLoading(true);
    try {
      await login(email.trim(), password);
      await refreshProfile();
      toast.success("Login successful!");
      navigate("/dashboard");
    } catch (err) {
      console.error("Login failed:", err);
      const msg =
        err.response?.data?.message ||
        err.response?.data?.detail ||
        "Invalid credentials";
      toast.error(msg);
    } finally {
      setLoading(false);
    }
  };

  //  existing structure — unchanged
  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">
          <div className="frmdata">
            <input
              type="email"
              placeholder="Email ID"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              disabled={loading}
            />
          </div>
          <div className="frmdata">
            <input
              type="password"
              placeholder="Password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              disabled={loading}
            />
          </div>
          <div className="frmdatabtn">
            <input
              type="submit"
              value={loading ? "Signing in..." : "Login"}
              disabled={loading}
            />
          </div>
          <div className="frmdatalnks">
            <span>
              <Link href="/auth/forget-password">Reset/Recover Password</Link>
            </span>
          </div>

        </div>
      </form>
    </div>
  );
}
