"use client";

import React, { useState, useEffect } from "react";
import IconLockDots from "@/components/icon/icon-lock-dots";
import { useRouter } from "next/navigation";
import axios from "axios";

interface ChangePasswordResponse {
  message?: string;
  error?: string;
}

const ComponentsAuthUnlockForm = () => {
  const router = useRouter();

  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");
  const [userEmail, setUserEmail] = useState<string | null>(null);
  const [redirecting, setRedirecting] = useState(false);

  // ✅ Load user email & verify auth
  useEffect(() => {
    // 🧠 Prevent running this effect after password update redirect starts
  if (redirecting) return;
    const token = localStorage.getItem("token");
    const email = localStorage.getItem("d4a_email");
    if (!token) {
      setError("You are not logged in. Redirecting to login...");
      setTimeout(() => router.push("/login"), 1500);
    } else {
      setUserEmail(email);
    }
  }, [router, redirecting]);

  const submitForm = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setSuccess("");

    const token = localStorage.getItem("token");
    const email = localStorage.getItem("d4a_email");
    if (!token || !email) {
      setError("Session expired or missing. Please log in again.");
      return;
    }

    if (!currentPassword || !newPassword) {
      setError("Please fill all fields.");
      return;
    }

    setLoading(true);
    try {
      const res = await axios.post<ChangePasswordResponse>(
        `https://ebay.backend.data4autos.com/api/auth/change-password`,
        { email, currentPassword, newPassword },
        {
          headers: { Authorization: `Bearer ${token}` },
        }
      );


      setSuccess(res.data.message || "Password updated successfully!");
      console.log("Password updated successfully, redirecting to login in 2 seconds...");
      setRedirecting(true); // ✅ prevents useEffect from running again

      setTimeout(() => {
        localStorage.removeItem("token");
        router.push("/login");
      }, 1200);

    } catch (err: any) {
      console.error("Change Password Error:", err);
      const msg =
        err.response?.data?.error ||
        err.response?.data?.message ||
        err.message ||
        "Something went wrong. Please try again.";

      if (msg.toLowerCase().includes("expired")) {
        setError("Session expired. Please log in again.");
        setTimeout(() => router.push("/login"), 1500);
      } else {
        setError(msg);
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <form className="space-y-5" onSubmit={submitForm}>
      {/* 🧩 User Info Header */}
      <div className="mb-10 flex items-center">
        <div className="flex h-16 w-16 items-end justify-center overflow-hidden rounded-full bg-[#00AB55] ltr:mr-4 rtl:ml-4">
          <img
            src="/assets/images/auth/user.jpg"
            className="w-full object-cover"
            alt="user"
          />
        </div>
        <div className="flex-1">
          <h4 className="text-2xl dark:text-white text-[#19d4fb]">{userEmail || "User"}</h4>
          {/* <p className="text-white">
            Enter your password to change your credentials
          </p> */}
        </div>
      </div>

      {/* 🔒 Current Password */}
      <div>
        <label htmlFor="currentPassword" className="dark:text-white">
          Current Password
        </label>
        <div className="relative text-white-dark">
          <input
            id="currentPassword"
            type="password"
            placeholder="Enter Current Password"
            className="form-input ps-10 placeholder:text-white-dark"
            value={currentPassword}
            onChange={(e) => setCurrentPassword(e.target.value)}
            required
          />
          <span className="absolute start-4 top-1/2 -translate-y-1/2">
            <IconLockDots fill={true} />
          </span>
        </div>
      </div>

      {/* 🔑 New Password */}
      <div>
        <label htmlFor="newPassword" className="dark:text-white">
          New Password
        </label>
        <div className="relative text-white-dark">
          <input
            id="newPassword"
            type="password"
            placeholder="Enter New Password"
            className="form-input ps-10 placeholder:text-white-dark"
            value={newPassword}
            onChange={(e) => setNewPassword(e.target.value)}
            required
          />
          <span className="absolute start-4 top-1/2 -translate-y-1/2">
            <IconLockDots fill={true} />
          </span>
        </div>
      </div>

      {error && <p className="text-red-500 text-sm">{error}</p>}
      {success && <p className="text-green-500 text-sm">{success}</p>}

      <button
        type="submit"
        disabled={loading}
        className="btn w-full border-0 uppercase shadow-[0_10px_20px_-10px_rgba(25,212,251,0.44)] disabled:cursor-not-allowed disabled:opacity-70 !mt-6 bg-[linear-gradient(135deg,#0EA5E9_0%,#19D4FB_50%,#67E8F9_100%)] text-white hover:bg-[linear-gradient(135deg,#67E8F9_0%,#19D4FB_50%,#0EA5E9_100%)]"
      >
        {loading ? "UPDATING…" : "CHANGE PASSWORD"}
      </button>
    </form>
  );
};

export default ComponentsAuthUnlockForm;
