// components/auth/VerifyOTPForm.tsx - FULLY FIXED
'use client';

import React, { useEffect, useRef, useState } from 'react';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import { useAppDispatch, useAppSelector } from '@/hooks/useRedux';
import Link from 'next/link';
import { Loader } from 'lucide-react';
import {
  verifyOTPFailure,
  verifyOTPStart,
  verifyOTPSuccess,
  resetErrorAndMessage,
  resendOTPStart,
  resendOTPSuccess,
  resendOTPFailure,
} from '@/lib/store/slices/userSlice';
import { verifyOTP, resendOTP } from '@/lib/api/client';
import { toast } from 'sonner';

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;

interface VerifyOTPFormProps {
  logoImage?: any;
  storeLinks?: any[];
  pageData?: any;
}

export function VerifyOTPForm({ logoImage, storeLinks = [], pageData }: VerifyOTPFormProps) {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { currentCustomer, loading } = useAppSelector((state) => state.user);
  
  const [otp, setOtp] = useState(["", "", "", ""]);
  const [timeLeft, setTimeLeft] = useState(0);
  const [otpExpiry, setOtpExpiry] = useState<string | null>(null);
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  const bgImage = pageData?.mainImage ? `${BASE_URL?.replace(/\/$/, "")}/${pageData?.mainImage?.replace(/^\//, "")}` : null;
  const headerLogo = logoImage?.headerLogo ? `${BASE_URL?.replace(/\/$/, "")}/${logoImage?.headerLogo?.replace(/^\//, "")}` : null;

  // ✅ Get OTP expiry from multiple sources
  useEffect(() => {
    // Check multiple sources for OTP expiry
    const expiryFromRedux = currentCustomer?.otpExpiry;
    const expiryFromStorage = localStorage.getItem("otpExpiry");
    const expiryFromForgot = sessionStorage.getItem("otpExpiry");
    
    const expiry = expiryFromRedux || expiryFromStorage || expiryFromForgot;
    
    if (expiry) {
      setOtpExpiry(expiry);
    } else {
      // Default 5 minutes from now
      const defaultExpiry = new Date(Date.now() + 5 * 60 * 1000).toISOString();
      setOtpExpiry(defaultExpiry);
    }
  }, [currentCustomer]);

  const calculateTimeLeft = () => {
    if (!otpExpiry) return 0;
    try {
      const expiryTime = new Date(otpExpiry).getTime();
      const now = Date.now();
      const diff = Math.floor((expiryTime - now) / 1000);
      return diff > 0 ? diff : 0;
    } catch (err) {
      console.error("Error calculating time left:", err);
      return 0;
    }
  };

  // ✅ Timer effect
  useEffect(() => {
    // Clear any existing timer
    if (timerRef.current) {
      clearInterval(timerRef.current);
      timerRef.current = null;
    }
    
    const initialTime = calculateTimeLeft();
    setTimeLeft(initialTime);
    
    if (initialTime > 0) {
      timerRef.current = setInterval(() => {
        setTimeLeft((prev) => {
          const newTime = prev - 1;
          if (newTime <= 0) {
            // Timer expired, clear interval
            if (timerRef.current) {
              clearInterval(timerRef.current);
              timerRef.current = null;
            }
            return 0;
          }
          return newTime;
        });
      }, 1000);
    }
    
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
        timerRef.current = null;
      }
    };
  }, [otpExpiry]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>, index: number) => {
    const value = e.target.value;
    if (!/^\d*$/.test(value)) return;
    const newOtp = [...otp];
    newOtp[index] = value.slice(-1);
    setOtp(newOtp);
    if (value && index < 3) {
      document.getElementById(`otp-${index + 1}`)?.focus();
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>, index: number) => {
    if (e.key === "Backspace" && !otp[index] && index > 0) {
      document.getElementById(`otp-${index - 1}`)?.focus();
    }
  };

  const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
    const pasteData = e.clipboardData.getData("text").trim();
    if (!/^\d+$/.test(pasteData)) return;

    const digits = pasteData.split("").slice(0, 4);
    const newOtp = ["", "", "", ""];

    digits.forEach((d, i) => (newOtp[i] = d));
    setOtp(newOtp);

    const lastIndex = digits.length - 1;
    document.getElementById(`otp-${lastIndex}`)?.focus();

    e.preventDefault();
  };

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    const otpValue = otp.join("");

    

    if (!otpValue) {
      const message = "OTP is required";
      dispatch(verifyOTPFailure(message));
      toast.error(message);
      return;
    }
    if (otpValue.length < 4) {
      const message = "OTP must be 4 digits";
      dispatch(verifyOTPFailure(message));
      toast.error(message);
      return;
    }
    
    dispatch(verifyOTPStart());
    let otpVerificationData: { otp: string; email: string; account?: boolean } = {};
    
    if (localStorage.getItem("email")) {
      otpVerificationData = {
        otp: otpValue,
        email: localStorage.getItem("email")!,
      };
    } else {
      otpVerificationData = {
        otp: otpValue,
        email: currentCustomer?.email!,
        account: true,
      };
    }
    
    console.log("🔍 VerifyOTPForm - Sending request:", otpVerificationData);
const result = await verifyOTP(otpVerificationData, logoImage?.securityKey);
console.log("🔍 VerifyOTPForm - Response:", result);
    
    if (result.success) {
      dispatch(verifyOTPSuccess(result.message));
      
      const message = localStorage.getItem("message");
      const email = localStorage.getItem("email");
      
      // Clear OTP expiry from storage
      localStorage.removeItem("otpExpiry");
      sessionStorage.removeItem("otpExpiry");
      
      // ✅ Forgot Password Flow
      if (email && message === 'forgot-password') {
        localStorage.removeItem("message");
        router.push("/update-password");
        toast.success("OTP Verified! Please set new password");
      } 
      // ✅ Signup Flow
      else if (email && message === 'signup') {
        localStorage.removeItem("message");
        localStorage.removeItem("email");
        router.push("/select-username");
        toast.success("OTP Verification Successful");
      } 
      // ✅ Login Flow (resend OTP for unverified account)
      else if (email && !message) {
        localStorage.removeItem("email");
        router.push("/");
        toast.success("OTP Verification Successful");
      } 
      // ✅ Default
      else {
        router.push("/");
        toast.success("OTP Verification Successful");
      }
    } else {
      dispatch(verifyOTPFailure(result.message));
      toast.error(result.message);
    }
  };

  const handleResend = async (event: React.MouseEvent) => {
    event.preventDefault();
    setOtp(["", "", "", ""]);
    dispatch(resendOTPStart());
    let email = currentCustomer?.email || localStorage.getItem("email");
    const message = localStorage.getItem("message");
    
    
      let key = 'login'; // default
  
  if (message === 'forgot-password') {
    key = 'forgot';
  } else if (message === 'signup') {
    key = 'signup';  // ✅ Signup ke liye "signup" bhejo
  }
    
    const result = await resendOTP(email!, logoImage?.securityKey, key);
    
    if (result.success) {
      dispatch(resendOTPSuccess(result.data));
      toast.success("OTP Sent Successfully");
      
      // ✅ Update OTP expiry from response
      if (result.data?.otpExpiry) {
        setOtpExpiry(result.data.otpExpiry);
        localStorage.setItem("otpExpiry", result.data.otpExpiry);
      } else {
        // Set default 5 minutes expiry
        const newExpiry = new Date(Date.now() + 5 * 60 * 1000).toISOString();
        setOtpExpiry(newExpiry);
        localStorage.setItem("otpExpiry", newExpiry);
      }
    } else {
      dispatch(resendOTPFailure(result.message));
      toast.error(result.message);
    }
  };

  useEffect(() => {
    dispatch(resetErrorAndMessage());
  }, [dispatch]);

  useEffect(() => {
    if (!currentCustomer?.email && !localStorage.getItem("email")) {
      router.push("/");
    }
  }, [currentCustomer, router]);

  const otpValue = otp.join("");
  const isOtpComplete = otpValue.length === 4 && otp.every((d) => d !== "");
  const isTimerExpired = timeLeft <= 0;
  
  // ✅ Button state logic
  const isVerifyDisabled = !isOtpComplete || isTimerExpired || loading;
  const isResendDisabled = !isTimerExpired || loading;

 

  return (
    <div className="w-full h-screen flex flex-col md:flex-row overflow-hidden">
      {/* 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} 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 - OTP 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">
        <div className="sm:w-sm md:w-md w-full mx-auto">
          <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">
            <p className="text-[20px] leading-[30px] font-semibold text-black">We sent you a code</p>
            <p className="text-[14px] leading-[24px] font-medium text-[#6D6D6D]">
              The verification code has been sent to this email id{' '}
              <span className="text-black font-semibold">{currentCustomer?.email || localStorage.getItem("email")}</span>
            </p>
          </div>
          <form onSubmit={handleSubmit} className="flex flex-col gap-2 w-full my-1">
            <div className="flex gap-2 items-center w-full justify-center">
              {otp.map((digit, idx) => (
                <div
                  key={idx}
                  className="p-[2px] bg-[#F7F7F7] rounded-md border border-black 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
                    type="text"
                    id={`otp-${idx}`}
                    value={digit}
                    onChange={(e) => handleChange(e, idx)}
                    onKeyDown={(e) => handleKeyDown(e, idx)}
                    onPaste={handlePaste}
                    maxLength={1}
                    className="w-6 sm:w-8 h-6 sm:h-8 bg-white text-black rounded-md text-center text-lg border-none outline-none"
                    disabled={loading}
                  />
                </div>
              ))}
            </div>
            <div className="flex w-full items-center justify-center">
              <p className="text-[14px] leading-[24px] font-medium text-[#6D6D6D]">
                Time left: {String(Math.floor(timeLeft / 60)).padStart(2, '0')}:{String(timeLeft % 60).padStart(2, '0')}
              </p>
            </div>
            <button
              disabled={isVerifyDisabled}
              type="submit"
              className={`text-white rounded-md w-full transition-colors duration-300 h-8 text-[14px] flex items-center justify-center leading-[24px] font-semibold ${
                isVerifyDisabled ? "bg-gray-400 cursor-not-allowed" : "bg-[#0084a5] cursor-pointer hover:bg-[#006d8a]"
              }`}
            >
              {loading ? <Loader className="w-6 h-6 text-white animate-spin" /> : "Verify"}
            </button>
          </form>
          <div className="flex w-full items-center justify-between cursor-pointer">
            <button
              type="button"
              onClick={handleResend}
              disabled={isResendDisabled}
              className={`text-[14px] leading-[24px] font-semibold ${
                isResendDisabled ? "text-gray-400 cursor-not-allowed" : "text-[#0084a5] cursor-pointer hover:underline"
              }`}
            >
              Resend Code
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}