// components/auth/ForgotPasswordForm.tsx
'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import { Loader, RefreshCcw } from 'lucide-react';
import { useAppDispatch, useAppSelector } from '@/hooks/useRedux';
import {
  resendOTPStart,
  resendOTPSuccess,
  resendOTPFailure,
  setEmailState,
  resetErrorAndMessage,
} from '@/lib/store/slices/userSlice';
import { resendOTP, getVerificationCaptcha, verifyCaptcha } from '@/lib/api/client';
import { validateEmail } from '@/lib/utils/helpers';
import { toast } from 'sonner';

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;
const SECURITY_KEY = process.env.NEXT_PUBLIC_SECURITY_KEY;

interface ForgotPasswordFormProps {
  logoImage?: any;
  storeLinks?: any[];
}

export function ForgotPasswordForm({ logoImage, storeLinks = [] }: ForgotPasswordFormProps) {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { loading } = useAppSelector((state) => state.user);
  
  const [email, setEmail] = useState('');
  const [captchaData, setCaptchaData] = useState({ svg: '' });
  const [captchaInput, setCaptchaInput] = useState('');
  const [captchaError, setCaptchaError] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  
  useEffect(() => {
    dispatch(resetErrorAndMessage());
    fetchCaptcha();
  }, [dispatch]);
  
  const fetchCaptcha = async () => {
    try {
      const result = await getVerificationCaptcha(logoImage?.securityKey || SECURITY_KEY);
      if (result.success && result.data?.captcha) {
        setCaptchaData({ svg: result.data.captcha });
        setCaptchaInput('');
        setCaptchaError('');
      }
    } catch (err) {
      toast.error('Failed to load CAPTCHA');
    }
  };
  
  const submitForm = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!email) {
      toast.error('Email is required');
      return;
    }
    
    if (!validateEmail(email)) {
      toast.error('Invalid email format');
      return;
    }
    
    if (!captchaInput) {
      setCaptchaError('Please enter CAPTCHA');
      return;
    }
    
    if (isSubmitting) return;
    
    setIsSubmitting(true);
    dispatch(resendOTPStart());
    
    try {
      // First verify captcha
      const captchaValid = await verifyCaptcha(captchaInput, logoImage?.securityKey || SECURITY_KEY);
      
      if (!captchaValid.success) {
        toast.error(captchaValid.message || 'CAPTCHA incorrect!');
        await fetchCaptcha();
        setIsSubmitting(false);
        dispatch(resendOTPFailure('Invalid CAPTCHA'));
        return;
      }
      
      // Captcha is valid, now send OTP
      const result = await resendOTP(email, logoImage?.securityKey || SECURITY_KEY, 'forgot', captchaInput);
      
 // In ForgotPasswordForm.tsx - submitForm function
if (result.success) {
  dispatch(resendOTPSuccess(result));
  dispatch(setEmailState(email));
  localStorage.setItem('email', email);
  localStorage.setItem('message', 'forgot-password');
  
  // ✅ Store OTP expiry from response
  if (result.data?.otpExpiry) {
    localStorage.setItem('otpExpiry', result.data.otpExpiry);
  } else if (result.data?.validFor) {
    // Calculate expiry from validFor minutes
    const expiryDate = new Date(Date.now() + (result.data.validFor * 60 * 1000)).toISOString();
    localStorage.setItem('otpExpiry', expiryDate);
  }
  
  toast.success('OTP Sent Successfully');
  router.push('/verify-otp');
}
else {
        dispatch(resendOTPFailure(result.message));
        toast.error(result.message);
        await fetchCaptcha();
      }
    } catch (err) {
      dispatch(resendOTPFailure('Failed to send OTP'));
      toast.error('Failed to send OTP');
      await fetchCaptcha();
    } finally {
      setIsSubmitting(false);
    }
  };
  
  const isFormValid = email && captchaInput;
  
  return (
    <div className="w-full flex items-center justify-center p-4">
      <div className="max-w-sm w-full bg-white/80 backdrop-blur-xl px-5 py-6 rounded-2xl shadow-lg">
        <div className="text-center mb-4">
          <span className="text-[20px] font-semibold text-[#1E222A] block">
            Forgot Password
          </span>
        </div>

        <form onSubmit={submitForm} className="space-y-4">
          {/* Email Input */}
          <div>
            <label className="text-[13px] text-[#1E222A]">
              Email Address <span className="text-red-500">*</span>
            </label>
            <input
              disabled={loading || isSubmitting}
              autoComplete="off"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="example@gmail.com"
              className="w-full p-3 bg-[#F8FAFC] rounded-lg outline-none text-[#77829D] text-[13px] border border-transparent focus:border-[#0084a5] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            />
          </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 flex items-center justify-center min-h-[40px] min-w-[100px] bg-[#F8FAFC] rounded-lg p-2"
                dangerouslySetInnerHTML={{ __html: captchaData.svg }}
              />
              <input
                type="text"
                value={captchaInput}
                onChange={(e) => setCaptchaInput(e.target.value)}
                placeholder="? "
                className="w-[80px] px-3 py-2.5 bg-[#F8FAFC] rounded-lg outline-none text-center text-[#77829D] text-sm border border-transparent focus:border-[#0084a5] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                disabled={loading || isSubmitting}
              />
              <button
                type="button"
                onClick={fetchCaptcha}
                disabled={loading || isSubmitting}
                className="p-2.5 cursor-pointer text-black bg-gray-200 rounded-lg hover:bg-gray-300 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <RefreshCcw size={16} />
              </button>
            </div>
            {captchaError && <p className="text-red-500 text-xs mt-1">{captchaError}</p>}
          </div>

          {/* Submit Button */}
          <button
            type="submit"
            disabled={!isFormValid || isSubmitting || loading}
            className="w-full py-1 cursor-pointer bg-[#0084a5] rounded-3xl text-white font-semibold text-[14px] hover:bg-[#006a85] transition-colors disabled:opacity-50 disabled:cursor-not-allowed mt-2"
          >
            {isSubmitting ? (
              <div className="flex items-center justify-center gap-2">
                <Loader size={16} className="animate-spin" />
                Sending OTP...
              </div>
            ) : (
              "Send OTP"
            )}
          </button>

          {/* Back to Login */}
          <p className="text-center text-[13px] text-[#1E222A] mt-1">
            Back to{" "}
            <Link
              href="/login"
              className={`cursor-pointer text-[#0084a5] font-medium hover:underline ${
                loading || isSubmitting ? "pointer-events-none opacity-50" : ""
              }`}
            >
              Login
            </Link>
          </p>
        </form>

        {/* App Store Buttons */}
        {storeLinks.length > 0 && (
          <div className="flex gap-2.5 justify-center mt-6">
            {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>
    </div>
  );
}