// components/auth/LoginForm.tsx
'use client';

import React, { useEffect, useState } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Eye, EyeOff, RefreshCcw } from 'lucide-react';
import { useAppDispatch, useAppSelector } from '@/hooks/useRedux';
import {
  signInFailure,
  signInStart,
  signInSuccess,
  resetErrorAndMessage,
  verifyOTPIfNotVerified,
  setHomePageData,
} from '@/lib/store/slices/userSlice';
import { getDynamicImages, getSideBarLabels, getVerificationCaptcha, loginCustomer } from '@/lib/api/client';
import { toast } from 'sonner';

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;
const ENV_SECURITY_KEY = process.env.NEXT_PUBLIC_SECURITY_KEY; // ✅ env wali key

interface LoginFormProps {
  loginPageData?: any;
  logoImage?: any;
  storeLinks?: any[];
}

export function LoginForm({ loginPageData, logoImage, storeLinks }: LoginFormProps) {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { loading } = useAppSelector((state) => state.user);

  const [logInData, setLogInData] = useState({ email: "", password: "" });
  const [showPassword, setShowPassword] = useState(false);
  const [captchaData, setCaptchaData] = useState({ svg: "" });
  const [captchaInput, setCaptchaInput] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [captchaError, setCaptchaError] = useState("");

  // ✅ Get the best available security key
  const getActiveSecurityKey = () => {
    // Pehle logoImage ki key use karo agar available hai
    if (logoImage?.securityKey) {
      return logoImage.securityKey;
    }
    // Nahi toh env wali key use karo
    if (ENV_SECURITY_KEY) {
      return ENV_SECURITY_KEY;
    }
    // Kuch nahi toh null
    return null;
  };

  // Fetch CAPTCHA on load - instantly with env key
  useEffect(() => {
    fetchCaptcha();
    dispatch(resetErrorAndMessage());
  }, []);

  const inputChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
    setLogInData(prev => ({ ...prev, [e.target.name]: e.target.value }));
    if (e.target.name === "captcha") {
      setCaptchaError("");
    }
  };

  // ✅ Fetch CAPTCHA with best available key
  const fetchCaptcha = async () => {
    const securityKey = getActiveSecurityKey();
    if (!securityKey) {
      console.error("No security key available");
      toast.error("Configuration error. Please refresh the page.");
      return;
    }
    
    try {
      const result = await getVerificationCaptcha(securityKey);
      if (result?.data?.captcha) setCaptchaData({ svg: result.data.captcha });
      setCaptchaInput("");
      setCaptchaError("");
    } catch (err) {
      console.error("Captcha fetch error:", err);
      toast.error("Failed to load CAPTCHA");
    }
  };

  // ✅ Verify CAPTCHA with best available key
  const verifyCaptchaHandler = async (userCaptcha: string) => {
    const securityKey = getActiveSecurityKey();
    if (!securityKey) {
      return { success: false, message: "Configuration error" };
    }
    
    try {
      const response = await fetch(`${BASE_URL}/captcha?securityKey=${securityKey}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({ captcha: userCaptcha })
      });

      const result = await response.json();
      return result;
    } catch (err) {
      return { success: false, message: "Error verifying CAPTCHA" };
    }
  };

  // ✅ Fetch home page data with best available key
  const fetchHomePageData = async () => {
    const securityKey = getActiveSecurityKey();
    if (!securityKey) return null;
    
    try {
      const response = await fetch(`${BASE_URL}/page/home-page?securityKey=${securityKey}`);
      const result = await response.json();
      if (result.success && result.data) {
        dispatch(setHomePageData(result.data));
        return result.data;
      }
      return null;
    } catch (error) {
      console.error("Failed to fetch home page data:", error);
      return null;
    }
  };

  const submitForm = async (e: React.FormEvent) => {
    e.preventDefault();
    console.log('1️⃣ Form submitted');
    if (isSubmitting || loading) return;
    if (!logInData.email || !logInData.password) return toast.error("Email and password are required");
    if (!captchaInput) {
      setCaptchaError("Please enter CAPTCHA");
      return;
    }

    setIsSubmitting(true);
    
    try {
      // Verify CAPTCHA
       console.log('2️⃣ Verifying captcha...');
  const captchaResult = await verifyCaptchaHandler(captchaInput);
  console.log('3️⃣ Captcha result:', captchaResult);
      
      if (!captchaResult.success) {
        console.log('4️⃣ Captcha failed');
        toast.error(captchaResult.message || "CAPTCHA is incorrect!");
        fetchCaptcha();
        setIsSubmitting(false);
        return;
      }

      dispatch(signInStart());
      const securityKey = getActiveSecurityKey();
        console.log('5️⃣ Calling login API...');
      const loginResult = await loginCustomer(logInData, securityKey);
        console.log('6️⃣ Login result:', loginResult);

      
      if (loginResult.locked || loginResult.status === 423) {
        toast.error(
          <div>
            <p className="font-bold">{loginResult.message}</p>
            <p className="mt-1">
              <Link href="/forgot-password" className="text-blue-600 underline">
                Click here to reset password and unlock account
              </Link>
            </p>
          </div>,
          { duration: 10000, closeButton: true }
        );
        dispatch(signInFailure(loginResult.message));
        fetchCaptcha();
        setIsSubmitting(false);
        return;
      }
      
      if (loginResult.attemptsRemaining >= 0 && !loginResult.success) {
        toast.warning(
          <div>
            <p>{loginResult.message}</p>
            {loginResult.attemptsRemaining === 1 && (
              <p className="text-red-600 font-bold mt-1">
                ⚠️ Last attempt! Account will be locked if failed.
              </p>
            )}
          </div>,
          { duration: 5000 }
        );
        dispatch(signInFailure(loginResult.message));
        fetchCaptcha();
        setIsSubmitting(false);
        return;
      }
      
      if (loginResult.success && loginResult.message?.includes("OTP")) {
        dispatch(verifyOTPIfNotVerified(loginResult.data));
        router.push("/verify-otp");
        toast.success(loginResult.message || "OTP sent successfully");
      } 
      else if (loginResult.success) {
        const homePageData = await fetchHomePageData();

        const [imageResult, labelsResult] = await Promise.all([
          getDynamicImages(securityKey).catch(err => {
            console.error("Failed to load dynamic images:", err);
            return { data: null };
          }),
          getSideBarLabels("Home", securityKey).catch(err => {
            console.error("Failed to load sidebar labels:", err);
            return { data: null };
          })
        ]);
        
        dispatch(
          signInSuccess({
            customer: loginResult.data,
            accessToken: loginResult.data.accessToken,  
            dynamicImages: imageResult?.data || {},
            labels: labelsResult?.data || {},
            homePageData: homePageData,
          })
        );
        toast.success(loginResult.message || "Login successful");
      } 
      else {
        dispatch(signInFailure(loginResult.message));
        toast.error(loginResult.message);
      }
    } catch (err) {
      console.error("Login error:", err);
      dispatch(signInFailure("Login failed"));
      toast.error("Login failed. Please try again.");
    } finally {
      setIsSubmitting(false);
    }
  };

  const isFormValid = logInData.email && logInData.password && captchaInput;

  return (
    <div className="max-w-sm mx-auto bg-white/80 backdrop-blur-xl px-5 md:py-5 rounded-2xl">
      <span className="text-[18px] text-center text-[#1E222A] block font-semibold">Login to Your Account</span>
      <p className="text-center text-[13px] text-[#6D6D6D] mt-1 mb-4">Access all features with your secure login.</p>
    
      <form className="space-y-3" onSubmit={submitForm}>
        {/* Email */}
        <div>
          <label className="text-[13px] text-[#1E222A]">Email address <span className="text-red-500">*</span></label>
          <input
            type="email"
            name="email"
            value={logInData.email}
            onChange={inputChangeHandler}
            placeholder="Enter your email"
            className="w-full p-2 bg-[#F8FAFC] rounded-lg outline-none text-[#1E222A] text-[12px] placeholder:text-[#77829D]"
          />
        </div>

        {/* Password */}
        <div>
          <label className="text-[13px] text-[#1E222A]">Password <span className="text-red-500">*</span></label>
          <div className="relative">
            <input
              type={showPassword ? "text" : "password"}
              name="password"
              value={logInData.password}
              onChange={inputChangeHandler}
              placeholder="********"
              className="w-full p-2 bg-[#F8FAFC] rounded-lg outline-none text-[#1E222A] text-[12px] placeholder:text-[#77829D]"
            />
            <span
              onClick={() => setShowPassword(!showPassword)}
              className="absolute inset-y-0 right-3 flex items-center text-[#77829D] cursor-pointer"
            >
              {showPassword ? <Eye size={16} /> : <EyeOff size={16} />}
            </span>
          </div>
        </div>

        {/* CAPTCHA */}
        <div>
          <label className="text-[13px] text-[#1E222A]">
            Captcha <span className="text-red-500">*</span>
          </label>
          
          <div className="flex items-center gap-3 mt-1">
            <div
              className="captcha-wrapper"
              dangerouslySetInnerHTML={{ __html: captchaData.svg }}
            />

            <input
              type="text"
              name="captcha"
              value={captchaInput}
              onChange={(e) => setCaptchaInput(e.target.value)}
              placeholder="Enter result"
              className="flex-1 px-3 py-2 bg-[#F8FAFC] outline-none rounded-lg text-sm text-[#1E222A] placeholder:text-[#77829D]"
            />

            <button
              type="button"
              onClick={fetchCaptcha}
              className="p-2 bg-gray-200 cursor-pointer text-black rounded-lg hover:bg-gray-300 transition-colors"
            >
              <RefreshCcw size={16} />
            </button>
          </div>
          
          {captchaError && (
            <p className="text-red-500 text-xs mt-1">{captchaError}</p>
          )}
        </div>

        <div className="flex justify-between text-[13px] mt-1">
          <label className="flex items-center gap-2 text-gray-700">
            <input type="checkbox" className='' /> Remember me
          </label>
          <Link href="/forgot-password" className="cursor-pointer text-[#0084a5]">
            Forgot Password?
          </Link>
        </div>

        <button
          type="submit"
          disabled={!isFormValid || isSubmitting}
          className="w-full cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed py-2 mt-0 bg-[#0084a5] rounded-3xl text-white font-semibold hover:bg-[#006a85] transition-colors"
        >
          {isSubmitting ? "Logging in..." : "Login"}
        </button>

        <p className="text-center text-black text-[13px]">
          New User? <Link href="/sign-up" className="cursor-pointer text-[#0084a5]">Create Account</Link>
        </p>
       
      </form>

      {/* App store buttons */}
      <div className="flex gap-2.5 justify-center mt-4">
        {storeLinks?.map((store: any) => (
          <Link 
            href={store?.socialLink} 
            target="_blank"
            key={store?._id}
            className="cursor-pointer transition-all duration-300 hover:shadow-lg hover:-translate-y-1"
          >
            <Image 
              width={100} 
              height={30} 
              src={`${BASE_URL}/${store?.socialIcon}`} 
              alt={store?.socialTitle || "Store"} 
              className="rounded-md"
            />
          </Link>
        ))}
      </div>
    </div>
  );
}