// components/auth/UpdatePasswordForm.tsx - WITH CLICK OUTSIDE HANDLER
'use client';

import React, { useState, useEffect, useRef } from "react";
import Image from "next/image";
import { Eye, EyeOff, Loader, Star, Check, X, RefreshCcw } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useDispatch, useSelector } from "react-redux";
import { toast } from "sonner";
import { updatePasswordStart, updatePasswordFailure, updatePasswordSuccess, resetErrorAndMessage } from "@/lib/store/slices/userSlice";
import { getVerificationCaptcha, updatePassword, verifyCaptcha } from "@/lib/api/client";

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;

interface UpdatePasswordFormProps {
  logoImage?: any;
  storeLinks?: any[];
  pageData?: any;
}

export function UpdatePasswordForm({ logoImage, storeLinks = [], pageData }: UpdatePasswordFormProps) {
  const { loading } = useSelector((state: any) => state.user);
  const dispatch = useDispatch();
  const router = useRouter();
  
  // Refs for click outside
  const newPasswordRef = useRef<HTMLDivElement>(null);
  const newPasswordTooltipRef = useRef<HTMLDivElement>(null);
  const confirmPasswordRef = useRef<HTMLDivElement>(null);
  const confirmPasswordTooltipRef = useRef<HTMLDivElement>(null);
  
  const [captchaData, setCaptchaData] = useState({ svg: "" });
  const [captchaInput, setCaptchaInput] = useState("");
  const [captchaError, setCaptchaError] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [isNewPasswordTouched, setIsNewPasswordTouched] = useState(false);
  const [reEnterNewPassword, setReEnterNewPassword] = useState("");
  const [showReEnterNewPassword, setShowReEnterNewPassword] = useState(false);
  const [isReEnterNewPasswordTouched, setReEnterNewPasswordTouched] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  
  const [newPasswordStrength, setNewPasswordStrength] = useState({
    hasSpecialChar: false,
    hasNumber: false,
    hasAlphabet: false,
    hasUppercase: false,
    hasMinLength: false,
  });

  const [reEnterNewPasswordStrength, setReEnterNewPasswordStrength] = useState({
    hasSpecialChar: false,
    hasNumber: false,
    hasAlphabet: false,
    hasUppercase: false,
    hasMinLength: false,
  });

  // ✅ Click outside handler
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      // Close new password tooltip
      if (
        newPasswordTooltipRef.current &&
        !newPasswordTooltipRef.current.contains(event.target as Node) &&
        newPasswordRef.current &&
        !newPasswordRef.current.contains(event.target as Node)
      ) {
        setIsNewPasswordTouched(false);
      }

      // Close confirm password tooltip
      if (
        confirmPasswordTooltipRef.current &&
        !confirmPasswordTooltipRef.current.contains(event.target as Node) &&
        confirmPasswordRef.current &&
        !confirmPasswordRef.current.contains(event.target as Node)
      ) {
        setReEnterNewPasswordTouched(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  const checkNewPasswordStrength = (password: string) => {
    setNewPasswordStrength({
      hasSpecialChar: /[\W_]/.test(password),
      hasNumber: /\d/.test(password),
      hasAlphabet: /[a-zA-Z]/.test(password),
      hasUppercase: /[A-Z]/.test(password),
      hasMinLength: password.length >= 8,
    });
  };

  const checkReEnterNewPasswordStrength = (password: string) => {
    setReEnterNewPasswordStrength({
      hasSpecialChar: /[\W_]/.test(password),
      hasNumber: /\d/.test(password),
      hasAlphabet: /[a-zA-Z]/.test(password),
      hasUppercase: /[A-Z]/.test(password),
      hasMinLength: password.length >= 8,
    });
  };

  const handleNewPasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setNewPassword(e.target.value);
    checkNewPasswordStrength(e.target.value);
    if (e.target.value) {
      setIsNewPasswordTouched(true);
    }
  };

  const handleReEnterNewPasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setReEnterNewPassword(e.target.value);
    checkReEnterNewPasswordStrength(e.target.value);
    if (e.target.value) {
      setReEnterNewPasswordTouched(true);
    }
  };
  
  const bgImage = pageData?.mainImage ? `${BASE_URL?.replace(/\/$/, "")}/${pageData?.mainImage?.replace(/^\//, "")}` : null;
  const headerLogo = logoImage?.headerLogo ? `${BASE_URL?.replace(/\/$/, "")}/${logoImage?.headerLogo?.replace(/^\//, "")}` : null;

  const fetchCaptcha = async () => {
    try {
      const result = await getVerificationCaptcha(logoImage?.securityKey);
      if (result.success && result.data?.captcha) {
        setCaptchaData({ svg: result.data.captcha });
        setCaptchaInput("");
        setCaptchaError("");
      }
    } catch (err) {
      console.error("Captcha fetch error:", err);
      toast.error("Error fetching CAPTCHA");
    }
  };

  const submitForm = async (event: React.FormEvent) => {
    event.preventDefault();
    
    if (isSubmitting || loading) return;
    
    if (!newPassword || !reEnterNewPassword) {
      toast.error("Please enter both password fields");
      return;
    }
    
    if (newPassword !== reEnterNewPassword) {
      toast.error("Passwords do not match");
      return;
    }
    
    if (!captchaInput) {
      setCaptchaError("Please enter CAPTCHA");
      return;
    }
    
    const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/;
    if (!passwordRegex.test(newPassword)) {
      toast.error("Password must be at least 8 characters long and include uppercase, lowercase, number, and special character.");
      return;
    }

    setIsSubmitting(true);
    
    try {
      // Step 1: Verify CAPTCHA first
      const captchaResult = await verifyCaptcha(captchaInput, logoImage?.securityKey);
      
      if (!captchaResult.success) {
        toast.error(captchaResult.message || "CAPTCHA is incorrect!");
        fetchCaptcha();
        setIsSubmitting(false);
        return;
      }

      // Step 2: If CAPTCHA is valid, proceed with password update
      dispatch(updatePasswordStart());
      
      const email = localStorage.getItem("email");
      
      if (!email) {
        toast.error("Email not found. Please try again.");
        router.push("/forgot-password");
        setIsSubmitting(false);
        return;
      }
      
      const dataToSubmit = {
        password: newPassword,
        email: email,
      };
      
      const result = await updatePassword(dataToSubmit, logoImage?.securityKey);
      
      if (result.success) {
        localStorage.removeItem("email");
        localStorage.removeItem("message");
        dispatch(updatePasswordSuccess(result.message));
        toast.success("Password Updated Successfully");
        router.push("/login");
      } else {
        dispatch(updatePasswordFailure(result.message));
        toast.error(result.message);
        fetchCaptcha();
      }
    } catch (error) {
      console.error("Password update error:", error);
      dispatch(updatePasswordFailure("An error occurred while updating password"));
      toast.error("An error occurred while updating password");
      fetchCaptcha();
    } finally {
      setIsSubmitting(false);
    }
  };

  useEffect(() => {
    fetchCaptcha();
  }, []);

  useEffect(() => {
    if (!localStorage.getItem("email")) {
      router.push("/forgot-password");
    }
  }, [router]);

  useEffect(() => {
    dispatch(resetErrorAndMessage());
  }, [dispatch]);

  const isPasswordValid = Object.values(newPasswordStrength).every(Boolean);
  const doPasswordsMatch = newPassword && reEnterNewPassword && newPassword === reEnterNewPassword;
  const isFormValid = newPassword && doPasswordsMatch && isPasswordValid && captchaInput;

  return (
    <div className="w-full h-screen flex flex-col md:flex-row overflow-hidden dark:text-black">
      {/* Left side with background image */}
      <div 
        className="w-full md:block hidden md:w-1/2 h-full bg-cover bg-center relative" 
        style={{ backgroundImage: `url(${bgImage})` }}
      >
        <Link href="/" className="flex justify-center items-center mx-auto w-24 mt-8">
          {headerLogo && (
            <Image width={500} height={500} priority quality={80} src={headerLogo} alt="Logo" className="w-full" />
          )}
        </Link>
        <div className="flex items-end w-full px-10 absolute bottom-7">
          <div className="flex justify-between items-center w-full">
            <p className="text-[14px] leading-[24px] text-white font-semibold">{logoImage?.copyright}</p>
            <div className="flex gap-2 items-center">
              {storeLinks?.map((store: any) => (
                <Link href={store?.socialLink} key={store?._id} target="_blank" className="w-28 cursor-pointer">
                  <Image width={500} height={500} priority quality={80} src={`${BASE_URL}/${store?.socialIcon}`} alt={store?.socialTitle || "Logo"} className="w-full rounded-sm" />
                </Link>
              ))}
            </div>
          </div>
        </div>
      </div>
      
      {/* Right side - Update Password Form */}
      <div className="w-full md:w-1/2 justify-center items-center h-full flex flex-col gap-2 bg-[#F5F5F5] sm:px-0 md:px-5 px-5 overflow-y-auto">
        <div className="w-full sm:w-sm mx-auto py-8">
          <Link href="/" className="md:hidden flex justify-center">
            {headerLogo && (
              <Image width={500} height={500} priority quality={80} src={headerLogo} alt="Logo" className="w-20" />
            )}
          </Link>
          
          <div className="w-full flex flex-col mb-4">
            <p className="text-[20px] leading-[30px] font-semibold text-black">Update Your Password</p>
            <p className="text-[14px] leading-[24px] font-medium text-[#6D6D6D]">
              Enter your new password below
            </p>
          </div>
          
          <form onSubmit={submitForm} className="flex flex-col gap-4 w-full">
            {/* New Password Field */}
            <div className="flex flex-col w-full relative" ref={newPasswordRef}>
              <div className="flex gap-0.5 mb-1">
                <p className="text-[12px] text-[#333333] leading-[22px]">New Password</p>
                <Star className="w-2 h-2 mt-1 text-red-500" fill="currentColor" />
              </div>
              <div className="flex items-center border-[1px] border-gray-300 rounded-md px-3 py-2 bg-white transition-all duration-300 ease-in-out focus-within:border-[#0084a5] focus-within:shadow-[0_0_8px_0_rgba(0,132,165,0.3)]">
                <input 
                  disabled={isSubmitting || loading} 
                  autoComplete="off" 
                  type={showNewPassword ? "text" : "password"} 
                  value={newPassword} 
                  onChange={handleNewPasswordChange} 
                  onFocus={() => setIsNewPasswordTouched(true)} 
                  placeholder="New Password" 
                  className="w-full border-none outline-none text-[12px] leading-[24px] placeholder:text-[12px] bg-transparent" 
                />
                <button 
                  type="button" 
                  onClick={() => setShowNewPassword(!showNewPassword)} 
                  className="ml-2 flex items-center justify-center cursor-pointer"
                >
                  {showNewPassword ? <Eye className="w-4 h-4 text-gray-600" /> : <EyeOff className="w-4 h-4 text-gray-600" />}
                </button>
              </div>
              
              {/* Password Strength Tooltip */}
              {isNewPasswordTouched && newPassword && (
                <div
                  ref={newPasswordTooltipRef}
                  className="flex flex-col w-60 p-3 rounded-xl z-10 absolute top-16 left-0 bg-white shadow-lg border border-gray-200"
                >
                  <div className="mb-2">
                    <div className="w-full bg-gray-200 rounded-full h-1.5">
                      <div 
                        className={`h-1.5 rounded-full transition-all duration-300 ${
                          Object.values(newPasswordStrength).filter(Boolean).length === 5 
                            ? "bg-green-500" 
                            : Object.values(newPasswordStrength).filter(Boolean).length >= 3 
                            ? "bg-yellow-500" 
                            : "bg-red-500"
                        }`} 
                        style={{ width: `${(Object.values(newPasswordStrength).filter(Boolean).length / 5) * 100}%` }}
                      />
                    </div>
                  </div>
                  {[
                    { key: "hasMinLength", label: "At least 8 characters" },
                    { key: "hasSpecialChar", label: "Contains special character" },
                    { key: "hasNumber", label: "Contains number" },
                    { key: "hasAlphabet", label: "Contains alphabet" },
                    { key: "hasUppercase", label: "Contains uppercase" },
                  ].map((item) => (
                    <div key={item.key} className="flex gap-2 items-center mb-1">
                      <div className={`w-4 h-4 p-0.5 rounded-full flex justify-center border ${
                        newPasswordStrength[item.key as keyof typeof newPasswordStrength] 
                          ? "border-green-600" 
                          : "border-red-500"
                      }`}>
                        {newPasswordStrength[item.key as keyof typeof newPasswordStrength] ? (
                          <Check className="w-3 h-3 text-green-600" />
                        ) : (
                          <X className="w-3 h-3 text-red-500" />
                        )}
                      </div>
                      <p className="text-xs text-gray-700">{item.label}</p>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* Confirm Password Field */}
            <div className="flex flex-col w-full relative" ref={confirmPasswordRef}>
              <div className="flex gap-0.5 mb-1">
                <p className="text-[12px] text-[#333333] leading-[22px]">Confirm Password</p>
                <Star className="w-2 h-2 mt-1 text-red-500" fill="currentColor" />
              </div>
              <div className="flex items-center border-[1px] border-gray-300 rounded-md px-3 py-2 bg-white transition-all duration-300 ease-in-out focus-within:border-[#0084a5] focus-within:shadow-[0_0_8px_0_rgba(0,132,165,0.3)]">
                <input 
                  disabled={isSubmitting || loading} 
                  autoComplete="off" 
                  type={showReEnterNewPassword ? "text" : "password"} 
                  value={reEnterNewPassword} 
                  onChange={handleReEnterNewPasswordChange} 
                  onFocus={() => setReEnterNewPasswordTouched(true)} 
                  placeholder="Confirm New Password" 
                  className="w-full border-none outline-none text-[12px] leading-[22px] placeholder:text-[12px] bg-transparent" 
                />
                <button 
                  type="button" 
                  onClick={() => setShowReEnterNewPassword(!showReEnterNewPassword)} 
                  className="ml-2 flex items-center justify-center cursor-pointer"
                >
                  {showReEnterNewPassword ? <Eye className="w-4 h-4 text-gray-600" /> : <EyeOff className="w-4 h-4 text-gray-600" />}
                </button>
              </div>
              
              {/* Password mismatch warning */}
              {reEnterNewPassword && newPassword !== reEnterNewPassword && (
                <p className="text-red-500 text-xs mt-1">Passwords do not match</p>
              )}
              
              {/* Confirm Password Strength Tooltip (optional - similar to new password) */}
              {isReEnterNewPasswordTouched && reEnterNewPassword && (
                <div
                  ref={confirmPasswordTooltipRef}
                  className="flex flex-col w-60 p-3 rounded-xl z-10 absolute top-16 left-0 bg-white shadow-lg border border-gray-200"
                >
                  <div className="mb-2">
                    <div className="w-full bg-gray-200 rounded-full h-1.5">
                      <div 
                        className={`h-1.5 rounded-full transition-all duration-300 ${
                          Object.values(reEnterNewPasswordStrength).filter(Boolean).length === 5 
                            ? "bg-green-500" 
                            : Object.values(reEnterNewPasswordStrength).filter(Boolean).length >= 3 
                            ? "bg-yellow-500" 
                            : "bg-red-500"
                        }`} 
                        style={{ width: `${(Object.values(reEnterNewPasswordStrength).filter(Boolean).length / 5) * 100}%` }}
                      />
                    </div>
                  </div>
                  {[
                    { key: "hasMinLength", label: "At least 8 characters" },
                    { key: "hasSpecialChar", label: "Contains special character" },
                    { key: "hasNumber", label: "Contains number" },
                    { key: "hasAlphabet", label: "Contains alphabet" },
                    { key: "hasUppercase", label: "Contains uppercase" },
                  ].map((item) => (
                    <div key={item.key} className="flex gap-2 items-center mb-1">
                      <div className={`w-4 h-4 p-0.5 rounded-full flex justify-center border ${
                        reEnterNewPasswordStrength[item.key as keyof typeof reEnterNewPasswordStrength] 
                          ? "border-green-600" 
                          : "border-red-500"
                      }`}>
                        {reEnterNewPasswordStrength[item.key as keyof typeof reEnterNewPasswordStrength] ? (
                          <Check className="w-3 h-3 text-green-600" />
                        ) : (
                          <X className="w-3 h-3 text-red-500" />
                        )}
                      </div>
                      <p className="text-xs text-gray-700">{item.label}</p>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* CAPTCHA Section */}
            <div className="flex flex-col w-full">
              <div className="flex gap-0.5 mb-1">
                <p className="text-[12px] text-[#333333] leading-[22px]">CAPTCHA</p>
                <Star className="w-2 h-2 mt-1 text-red-500" fill="currentColor" />
              </div>
              <div className="flex items-center gap-3">
                <div 
                  className="captcha-wrapper flex items-center justify-center min-h-[40px] min-w-[100px] bg-white rounded-lg p-2 border border-gray-300"
                  dangerouslySetInnerHTML={{ __html: captchaData.svg }} 
                />
                <input 
                  disabled={isSubmitting || loading} 
                  type="text" 
                  value={captchaInput} 
                  onChange={(e) => {
                    setCaptchaInput(e.target.value);
                    setCaptchaError("");
                  }} 
                  placeholder="Enter code" 
                  className="flex-1 px-3 py-2 bg-white rounded-lg outline-none text-center text-sm border border-gray-300 focus:border-[#0084a5] transition-colors disabled:opacity-50"
                />
                <button 
                  type="button" 
                  onClick={fetchCaptcha} 
                  disabled={isSubmitting || loading}
                  className="p-2 bg-gray-200 rounded-lg hover:bg-gray-300 transition-colors disabled:opacity-50 cursor-pointer"
                >
                  <RefreshCcw size={16} />
                </button>
              </div>
              {captchaError && (
                <p className="text-red-500 text-xs mt-1">{captchaError}</p>
              )}
            </div>

            {/* Submit Button */}
            <button 
              disabled={isSubmitting || loading || !isFormValid} 
              type="submit" 
              className={`text-white rounded-md w-full transition-colors duration-300 h-10 text-[14px] flex items-center justify-center leading-[24px] font-semibold mt-2 ${
                isFormValid && !isSubmitting && !loading 
                  ? "bg-[#0084a5] cursor-pointer hover:bg-[#006d8a]" 
                  : "bg-gray-400 cursor-not-allowed"
              }`}
            >
              {isSubmitting || loading ? <Loader className="w-5 h-5 text-white animate-spin" /> : "Update Password"}
            </button>

            {/* Back to Login */}
            <p className="text-center text-[13px] text-[#1E222A] mt-2">
              Remember your password?{" "}
              <Link href="/login" className="text-[#0084a5] font-medium hover:underline cursor-pointer">
                Back to Login
              </Link>
            </p>
          </form>
        </div>
      </div>
    </div>
  );
}