'use client';
import IconLockDots from '@/components/icon/icon-lock-dots';
import { useRouter } from 'next/navigation';
import React, {useState, useEffect} from 'react';
import axios from 'axios';
import { Eye, EyeOff } from "lucide-react";
import { ApiServerBaseUrl } from '@/utils/baseurl.utils';

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);
  const [showPassword, setShowPassword] = useState(false);
const [showPassword1, setShowPassword1] = useState(false);

interface ChangePasswordResponse {
  message?: string;
  error?: string;
}
  // ✅ 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>(
        `${ApiServerBaseUrl}/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}>
            <div>
                <label htmlFor="Password" className="dark:text-white">
                    Current Password
                </label>
                <div className="relative text-white-dark">
                    <input 
                    id="currentPassword"
                    type={showPassword ? "text" : "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>
                    {/* 👁️ Eye toggle (right) */}
                    <button
                        type="button"
                        className="absolute end-3 top-1/2 -translate-y-1/2 text-gray-400"
                        onClick={() => setShowPassword(!showPassword)}
                    >
                        {showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                    </button>
                </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={showPassword1 ? "text" : "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>
                 {/* 👁️ Eye toggle (right) */}
                <button
                type="button"
                className="absolute end-3 top-1/2 -translate-y-1/2 text-gray-400"
                onClick={() => setShowPassword1(!showPassword1)}
                >
                {showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                </button>
                </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 btn-gradient !mt-6 w-full border-0 uppercase shadow-[0_10px_20px_-10px_rgba(67,97,238,0.44)]">
               {loading ? "UPDATING…" : "CHANGE PASSWORD"}
            </button>
        </form>
    );
};

export default ComponentsAuthUnlockForm;
