import React, { useState, useEffect, useRef } from "react";
import { useParams } from "next/navigation";
import useNavigate from "@/hooks/useNavigate";
import { toast } from "react-toastify";
import {
  confirmPasswordReset,
  checkPasswordReset,
} from "@/services/authService";
import { assetPath } from "../../utils/assetPath";
import Link from "next/link";

export default function ResetPassword() {
  const { uid, token } = useParams();

  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [checkingToken, setCheckingToken] = useState(true);
  const [tokenValid, setTokenValid] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");

  const navigate = useNavigate();

  // ✅ IMPORTANT: prevent double API call
  const hasCheckedToken = useRef(false);

  useEffect(() => {
    document.body.classList.add("loginbner");

    const verifyToken = async () => {
      if (hasCheckedToken.current) return; // ✅ stop re-call
      hasCheckedToken.current = true;

      try {
        const res = await checkPasswordReset(uid, token);

        if (res?.data?.detail === "URL is valid.") {
          setTokenValid(true);
          setErrorMessage("");
        } else {
          const message =
            res?.data?.detail || "Invalid or expired password reset link";

          setErrorMessage(message);
          toast.error(message);

          setTimeout(() => {
            navigate("/"); // ❌ still root only for invalid token
          }, 1500);
        }
      } catch (err) {
        const message =
          err?.response?.data?.detail ||
          err?.response?.data?.message ||
          "Invalid or expired password reset link";

        setErrorMessage(message);
        toast.error(message);

        setTimeout(() => {
          navigate("/");
        }, 1500);
      } finally {
        setCheckingToken(false);
      }
    };

    if (uid && token) {
      verifyToken();
    } else {
      toast.error("Invalid password reset link");
      navigate("/");
    }

    return () => {
      document.body.classList.remove("loginbner");
    };
  }, [uid, token, navigate]);

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

    if (loading) return;

    if (!tokenValid) {
      toast.error("Invalid or expired password reset link");
      return;
    }

    if (!password || !confirmPassword) {
      toast.warn("Please fill all fields");
      return;
    }

    if (password !== confirmPassword) {
      toast.error("Passwords do not match");
      return;
    }

    setLoading(true);

    try {
      await confirmPasswordReset(uid, token, password);

      toast.success("Password updated successfully!");

      // ✅ FIX: go ONLY to login page
      navigate("/auth/login");

    } catch (err) {
      const message =
        err?.response?.data?.detail ||
        err?.response?.data?.message ||
        "Failed to reset password";

      setErrorMessage(message);
      toast.error(message);
    } finally {
      setLoading(false);
    }
  };

  if (checkingToken) {
    return (
      <div className="loginpnel">
        <div className="loginform text-center">
          <div className="loginlgo">
            <img src={assetPath("/assets/images/jury_intel_logo.png")} />
          </div>

          <div className="loginfrminr">
            <div
              className="spinner-border mb-3"
              role="status"
              style={{
                borderColor: "#0D3156",
                borderRightColor: "transparent",
              }}
            ></div>

            <h5>Verifying password reset link...</h5>
          </div>
        </div>
      </div>
    );
  }

  if (!tokenValid) {
    return (
      <div className="loginpnel">
        <div className="loginform text-center">
          <div className="loginlgo">
            <img src={assetPath("/assets/images/jury_intel_logo.png")} />
          </div>

          <div className="loginfrminr">
            <div
              className="spinner-border mb-3"
              role="status"
              style={{
                borderColor: "#0D3156",
                borderRightColor: "transparent",
              }}
            ></div>

            <h5>
              {errorMessage
                ? `${errorMessage}, Redirecting...`
                : "URL is invalid, Redirecting..."}
            </h5>
          </div>
        </div>
      </div>
    );
  }

  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" }}>
            Reset Password
          </h3>

          <div className="frmdata">
            <input
              type="password"
              placeholder="Enter new password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              disabled={loading}
            />
          </div>

          <div className="frmdata">
            <input
              type="password"
              placeholder="Confirm new password"
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
              disabled={loading}
            />
          </div>

          <div className="frmdatabtn">
            <input
              type="submit"
              value={loading ? "Updating..." : "Update Password"}
              disabled={loading}
            />
          </div>

          <div className="frmdatalnks">
            <span>
              <Link href="/auth/login">Back to Login</Link>
            </span>
          </div>
        </div>
      </form>
    </div>
  );
}