'use client';

import React, { useEffect, useRef, useState } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import {
  Eye,
  EyeOff,
  Loader,
  RefreshCcw,
  Check,
  X,
  ChevronDown,
} from 'lucide-react';
import { useAppDispatch, useAppSelector } from '@/hooks/useRedux';
import {
  signUpFailure,
  signUpStart,
  signUpSuccess,
  resetErrorAndMessage,
} from '@/lib/store/slices/userSlice';
import {
  signUpCustomer,
  countryList,
  getVerificationCaptcha,
  getLabelsByScreenAndType,
} from '@/lib/api/client';
import {
  detectCountry,
  formatDobForSubmission,
} from '@/lib/utils/helpers';
import { toast } from 'sonner';

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;

interface IndividualFormProps {
  signUpPageData?: any;
  countryDataList?: any[];
  logoImage?: any;
  storeLinks?: any[];
  onSuccess?: (userData: any) => void;
}

export function IndividualForm({ signUpPageData, countryDataList, logoImage, storeLinks, onSuccess }: IndividualFormProps) {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const customer = useAppSelector((state) => state.user);

  // Dynamic Labels
  const [labels, setLabels] = useState({
    personalInfo: {} as Record<string, string>,
    formButtons: {} as Record<string, string>,
  });
  const [isLoadingLabels, setIsLoadingLabels] = useState(true);
  
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [selectedImage, setSelectedImage] = useState("");
  const [captchaData, setCaptchaData] = useState({ svg: "" });
  const [captchaInput, setCaptchaInput] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [confirmPassword, setConfirmPassword] = useState("");
  const [isPasswordFieldTouched, setIsPasswordFieldTouched] = useState(false);
  const [isConfirmPasswordFieldTouched, setIsConfirmPasswordFieldTouched] = useState(false);
  const [captchaError, setCaptchaError] = useState("");
  const [showCountryDropdown, setShowCountryDropdown] = useState(false);
  const [countriesState, setCountriesState] = useState<any[]>([]);

  const passwordRef = useRef<HTMLDivElement>(null);
  const confirmPasswordRef = useRef<HTMLDivElement>(null);
  const passwordTooltipRef = useRef<HTMLDivElement>(null);
  const confirmPasswordTooltipRef = useRef<HTMLDivElement>(null);
  const countryDropdownRef = useRef<HTMLDivElement>(null);

  const [passwordStrength, setPasswordStrength] = useState({
    hasSpecialChar: false,
    hasNumber: false,
    hasAlphabet: false,
    hasUppercase: false,
    hasMinLength: false,
  });

  const [confirmPasswordStrength, setConfirmPasswordStrength] = useState({
    hasSpecialChar: false,
    hasNumber: false,
    hasAlphabet: false,
    hasUppercase: false,
    hasMinLength: false,
  });

  const [signUpData, setSignUpData] = useState({
    fullName: "",
    email:"",
    password: "",
    phone: "",
    dateOfBirth: "",
    countryCode: "+91",
    country: "",
    termsConditions: false,
    ip: "",
    deviceType: "",
  });

  const isPasswordValid = Object.values(passwordStrength).every(Boolean);
  const doPasswordsMatch =
    signUpData.password &&
    confirmPassword &&
    signUpData.password === confirmPassword;

  // Fetch dynamic labels
  useEffect(() => {
    const fetchLabels = async () => {
      try {
        const result = await getLabelsByScreenAndType('beforlogin', 'individual', logoImage?.securityKey);
        
        if (result.success && result.data) {
          const labelsData = {
            personalInfo: {} as Record<string, string>,
            formButtons: {} as Record<string, string>,
          };
          
          result.data.forEach((item: any) => {
            if (item.section === 'personal_information') {
              labelsData.personalInfo[item.label] = item.value;
            } else if (item.section === 'form_buttons') {
              labelsData.formButtons[item.label] = item.value;
            }
          });
          
          setLabels(labelsData);
        }
        setIsLoadingLabels(false);
      } catch (error) {
        console.error('Failed to fetch labels:', error);
        setIsLoadingLabels(false);
      }
    };
    
    fetchLabels();
  }, [logoImage?.securityKey]);

  // Handle click outside to close tooltips and dropdown
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        passwordTooltipRef.current &&
        !passwordTooltipRef.current.contains(event.target as Node) &&
        passwordRef.current &&
        !passwordRef.current.contains(event.target as Node)
      ) {
        setIsPasswordFieldTouched(false);
      }

      if (
        confirmPasswordTooltipRef.current &&
        !confirmPasswordTooltipRef.current.contains(event.target as Node) &&
        confirmPasswordRef.current &&
        !confirmPasswordRef.current.contains(event.target as Node)
      ) {
        setIsConfirmPasswordFieldTouched(false);
      }

      if (
        countryDropdownRef.current &&
        !countryDropdownRef.current.contains(event.target as Node)
      ) {
        setShowCountryDropdown(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  const inputChangeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type, checked } = event.target;
    setSignUpData((prevData) => {
      let newValue = type === "checkbox" ? checked : value;
      if (name === "email") {
        newValue = value.toLowerCase();
      }
      if (name === "dateOfBirth" && value) {
        newValue = value;
      }
      return { ...prevData, [name]: newValue as any };
    });
  };

  const checkPasswordStrength = (password: string) => {
    setPasswordStrength({
      hasSpecialChar: /[\W_]/.test(password),
      hasNumber: /\d/.test(password),
      hasAlphabet: /[a-zA-Z]/.test(password),
      hasUppercase: /[A-Z]/.test(password),
      hasMinLength: password.length >= 8,
    });
  };

  const handlePasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    inputChangeHandler(e);
    checkPasswordStrength(e.target.value);
    if (e.target.value) {
      setIsPasswordFieldTouched(true);
    }
  };

  const checkConfirmPasswordStrength = (password: string) => {
    setConfirmPasswordStrength({
      hasSpecialChar: /[\W_]/.test(password),
      hasNumber: /\d/.test(password),
      hasAlphabet: /[a-zA-Z]/.test(password),
      hasUppercase: /[A-Z]/.test(password),
      hasMinLength: password.length >= 8,
    });
  };

  const handleConfirmPasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setConfirmPassword(e.target.value);
    checkConfirmPasswordStrength(e.target.value);
    if (e.target.value) {
      setIsConfirmPasswordFieldTouched(true);
    }
  };

  const fetchCountryList = async () => {
    try {
      const result = await countryList(logoImage?.securityKey);
      const countriesData = result?.data || [];
      setCountriesState(countriesData);
      
      const response = await detectCountry();

      setSignUpData((prev) => ({
        ...prev,
        ip: response?.ip || "",
        deviceType: "Web",
      }));
      
      const selectedCountry = countriesData.find(
        (item: any) =>
          item?.countryName?.toLowerCase() === response?.country_name?.toLowerCase()
      );
      
      if (selectedCountry) {
        const countryCode = selectedCountry?.countryCode || "+91";
        const countryName = selectedCountry?.countryName || "";
        const flag = selectedCountry?.countryFlag || "";
        
        setSignUpData((prev) => ({
          ...prev,
          countryCode: countryCode,
          country: countryName,
        }));
        setSelectedImage(flag);
      }
    } catch (err) {
      console.error("Error fetching country list:", err);
    }
  };

  const selectCountry = (country: any) => {
    const countryCode = country?.countryCode || "+91";
    const countryName = country?.countryName || "";
    const flag = country?.countryFlag || "";
    
    setSignUpData((prev) => ({
      ...prev,
      countryCode: countryCode,
      country: countryName,
    }));
    setSelectedImage(flag);
    setShowCountryDropdown(false);
  };

  const fetchCaptcha = async () => {
    try {
      const result = await getVerificationCaptcha(logoImage?.securityKey);
      if (result?.data?.captcha) setCaptchaData({ svg: result.data.captcha });
      setCaptchaInput("");
      setCaptchaError("");
    } catch (err) {
      toast.error("Failed to load CAPTCHA");
    }
  };

  const verifyCaptchaHandler = async (userCaptcha: string) => {
    try {
      const response = await fetch(`${BASE_URL}/captcha?securityKey=${logoImage?.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" };
    }
  };

  const submitForm = async (event: React.FormEvent) => {
    event.preventDefault();
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/;
    const phoneRegex = /^[0-9]+$/;
    const nameRegex = /^[A-Za-z\s]+$/;
    const trimmedName = signUpData.fullName.trim();

    if (
      !signUpData.email ||
      !signUpData.password ||
      !signUpData.fullName ||
      !signUpData.phone ||
      !signUpData.dateOfBirth ||
      !signUpData.countryCode
    ) {
      const message = "All fields required.";
      dispatch(signUpFailure(message));
      toast.error(message);
      return;
    }
    if (!nameRegex.test(trimmedName)) {
      const message = "Full Name can only contain letters and spaces (no numbers or special characters).";
      dispatch(signUpFailure(message));
      toast.error(message);
      return;
    }
    if (!emailRegex.test(signUpData.email)) {
      const message = "Invalid Email Format";
      dispatch(signUpFailure(message));
      toast.error(message);
      return;
    }
    if (
      signUpData.phone.length < 10 ||
      signUpData.phone.length > 12 ||
      !phoneRegex.test(signUpData.phone)
    ) {
      const message = "Phone number must be between 10 to 12 characters (numbers only).";
      dispatch(signUpFailure(message));
      toast.error(message);
      return;
    }
    if (!passwordRegex.test(signUpData.password)) {
      const message = "Password must be at least 8 characters and include one uppercase, one lowercase, one number, and one special character.";
      dispatch(signUpFailure(message));
      toast.error(message);
      return;
    }
    if (signUpData.password !== confirmPassword) {
      const message = "Passwords do not match";
      dispatch(signUpFailure(message));
      toast.error(message);
      return;
    }
    const today = new Date();
    const dob = new Date(signUpData.dateOfBirth);
    let age = today.getFullYear() - dob.getFullYear();
    const monthDiff = today.getMonth() - dob.getMonth();
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < dob.getDate())) {
      age--;
    }
    if (age < 18) {
      const message = "You must be at least 18 years old to sign up.";
      dispatch(signUpFailure(message));
      toast.error(message);
      return;
    }
    if (!signUpData.termsConditions) {
      const message = "Accept Terms & Conditions and Privacy Policy";
      dispatch(signUpFailure(message));
      toast.error(message);
      return;
    }
    if (!captchaInput) {
      setCaptchaError("Please enter CAPTCHA");
      return;
    }

    setIsSubmitting(true);

    try {
      const captchaResult = await verifyCaptchaHandler(captchaInput);

      if (!captchaResult.success) {
        toast.error(captchaResult.message || "CAPTCHA is incorrect!");
        fetchCaptcha();
        setIsSubmitting(false);
        return;
      }

      dispatch(signUpStart());
      const dataToSubmit = {
        ...signUpData,
        dateOfBirth: formatDobForSubmission(signUpData.dateOfBirth),
      };
      const result = await signUpCustomer(dataToSubmit, logoImage?.securityKey);
      if (result?.success) {
        const customerData = result.data;
        dispatch(signUpSuccess(customerData));
        toast.success(result?.message);
          // ✅ Store email for OTP verification
  localStorage.setItem('email', signUpData.email);
  localStorage.setItem('message', 'signup');
        if (onSuccess) {
          onSuccess(customerData);
        } else {
          router.push("/verify-otp");
        }
      } else {
        dispatch(signUpFailure(result.message));
        toast.error(result.message);
      }
    } catch (err) {
      dispatch(signUpFailure("Signup failed"));
      toast.error("Signup failed");
    } finally {
      setIsSubmitting(false);
    }
  };

  useEffect(() => {
    fetchCaptcha();
    fetchCountryList();
  }, []);

  useEffect(() => {
    dispatch(resetErrorAndMessage());
  }, [dispatch]);

  // useEffect(() => {
  //   if (customer?.currentCustomer?.email) {
  //     setSignUpData((prev) => ({ ...prev, email: customer.currentCustomer?.email || "" }));
  //   }
  // }, [customer?.currentCustomer?.email]);

  const isFormValid =
    signUpData.fullName &&
    signUpData.email &&
    isPasswordValid &&
    doPasswordsMatch &&
    signUpData.phone &&
    signUpData.dateOfBirth &&
    signUpData.termsConditions &&
    captchaInput;

  // Show skeleton while loading labels
  if (isLoadingLabels) {
    return (
      <div className="w-full max-h-[70vh] overflow-y-auto pr-1">
        <div className="space-y-3 animate-pulse">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-2">
            <div><div className="h-2 w-16 bg-gray-200 rounded mb-1"></div><div className="h-9 bg-gray-200 rounded-lg"></div></div>
            <div><div className="h-2 w-20 bg-gray-200 rounded mb-1"></div><div className="h-9 bg-gray-200 rounded-lg"></div></div>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-2">
            <div><div className="h-2 w-14 bg-gray-200 rounded mb-1"></div><div className="h-9 bg-gray-200 rounded-lg"></div></div>
            <div><div className="h-2 w-20 bg-gray-200 rounded mb-1"></div><div className="h-9 bg-gray-200 rounded-lg"></div></div>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-2">
            <div><div className="h-2 w-20 bg-gray-200 rounded mb-1"></div><div className="h-9 bg-gray-200 rounded-lg"></div></div>
            <div><div className="h-2 w-16 bg-gray-200 rounded mb-1"></div><div className="h-9 bg-gray-200 rounded-lg"></div></div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="w-full max-h-[78vh] overflow-y-auto pr-1 scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100">
      <form className="space-y-1" onSubmit={submitForm}>
        {/* Full Name */}
        <div>
          <label className="text-[13px] text-[#1E222A]">
            {labels.personalInfo.full_name || 'Full Name'} <span className="text-red-500">*</span>
          </label>
          <input
            disabled={customer?.loading || isSubmitting}
            type="text"
            name="fullName"
            value={signUpData.fullName}
            onChange={inputChangeHandler}
            placeholder={labels.personalInfo.full_name_placeholder || 'Enter your full name'}
            className="w-full p-3 bg-[#F8FAFC] rounded-lg outline-none text-[#1E222A] text-sm"
          />
        </div>

        {/* Email Address */}
        <div>
          <label className="text-[13px] text-[#1E222A]">
            {labels.personalInfo.email || 'Email Address'} <span className="text-red-500">*</span>
          </label>
          <input
            disabled={customer?.loading || isSubmitting}
            type="email"
            name="email"
            value={signUpData.email}
            onChange={inputChangeHandler}
            placeholder={labels.personalInfo.email_placeholder || 'Enter your email'}
            className="w-full p-3 bg-[#F8FAFC] rounded-lg outline-none text-[#1E222A] text-sm"
          />
        </div>

        {/* Password and Confirm Password */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {/* Password */}
          <div className="relative">
            <label className="text-[13px] text-[#1E222A]">
              {labels.personalInfo.password || 'Password'} <span className="text-red-500">*</span>
            </label>
            <div className="relative" ref={passwordRef}>
              <input
                disabled={customer?.loading || isSubmitting}
                type={showPassword ? "text" : "password"}
                name="password"
                value={signUpData.password}
                onChange={handlePasswordChange}
                onFocus={() => setIsPasswordFieldTouched(true)}
                placeholder="********"
                className="w-full p-3 bg-[#F8FAFC] rounded-lg outline-none text-[#1E222A] text-sm pr-10"
              />
              <span
                onClick={() => setShowPassword(!showPassword)}
                className="absolute inset-y-0 right-3 flex items-center text-[#77829D] cursor-pointer"
              >
                {showPassword ? <Eye size={18} /> : <EyeOff size={18} />}
              </span>
            </div>

            {/* Password Strength Tooltip */}
            {isPasswordFieldTouched && signUpData?.password && (
              <div
                ref={passwordTooltipRef}
                className="absolute z-50 w-full mt-1 p-3 rounded-lg 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(passwordStrength).filter(Boolean).length === 5
                          ? "bg-green-500"
                          : Object.values(passwordStrength).filter(Boolean).length >= 3
                          ? "bg-yellow-500"
                          : "bg-red-500"
                      }`}
                      style={{
                        width: `${(Object.values(passwordStrength).filter(Boolean).length / 5) * 100}%`,
                      }}
                    ></div>
                  </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 ${
                        passwordStrength[item.key as keyof typeof passwordStrength]
                          ? "border-green-600"
                          : "border-red-500"
                      }`}
                    >
                      {passwordStrength[item.key as keyof typeof passwordStrength] ? (
                        <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 */}
          <div className="relative">
            <label className="text-[13px] text-[#1E222A]">
              {labels.personalInfo.confirm_password || 'Confirm Password'} <span className="text-red-500">*</span>
            </label>
            <div className="relative" ref={confirmPasswordRef}>
              <input
                disabled={customer?.loading || isSubmitting}
                type={showConfirmPassword ? "text" : "password"}
                value={confirmPassword}
                onChange={handleConfirmPasswordChange}
                onFocus={() => setIsConfirmPasswordFieldTouched(true)}
                placeholder="********"
                className={`w-full p-3 bg-[#F8FAFC] rounded-lg outline-none text-[#1E222A] text-sm pr-10 ${
                  confirmPassword && !doPasswordsMatch ? "border border-red-500" : ""
                }`}
              />
              <span
                onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                className="absolute inset-y-0 right-3 flex items-center text-[#77829D] cursor-pointer"
              >
                {showConfirmPassword ? <Eye size={18} /> : <EyeOff size={18} />}
              </span>
            </div>

            {/* Confirm Password Strength Tooltip */}
            {isConfirmPasswordFieldTouched && confirmPassword && (
              <div
                ref={confirmPasswordTooltipRef}
                className={`absolute z-50 w-full mt-1 p-3 rounded-lg bg-white shadow-lg border ${
                  !doPasswordsMatch ? "border-red-500" : "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(confirmPasswordStrength).filter(Boolean).length === 5
                          ? "bg-green-500"
                          : Object.values(confirmPasswordStrength).filter(Boolean).length >= 3
                          ? "bg-yellow-500"
                          : "bg-red-500"
                      }`}
                      style={{
                        width: `${(Object.values(confirmPasswordStrength).filter(Boolean).length / 5) * 100}%`,
                      }}
                    ></div>
                  </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" },
                  { key: "match", label: "Passwords match", custom: doPasswordsMatch },
                ].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 ${
                        item.custom !== undefined
                          ? item.custom
                            ? "border-green-600"
                            : "border-red-500"
                          : confirmPasswordStrength[item.key as keyof typeof confirmPasswordStrength]
                          ? "border-green-600"
                          : "border-red-500"
                      }`}
                    >
                      {item.custom !== undefined ? (
                        item.custom ? (
                          <Check className="w-3 h-3 text-green-600" />
                        ) : (
                          <X className="w-3 h-3 text-red-500" />
                        )
                      ) : confirmPasswordStrength[item.key as keyof typeof confirmPasswordStrength] ? (
                        <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>
        </div>

        {/* Mobile Number and Date of Birth */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {/* Mobile Number with Dropdown */}
          <div ref={countryDropdownRef}>
            <label className="text-[13px] text-[#1E222A]">
              {labels.personalInfo.mobile_number || 'Mobile Number'} <span className="text-red-500">*</span>
            </label>
            <div className="flex items-center bg-[#F8FAFC] rounded-lg h-[44px]">
              <div className="relative flex-shrink-0">
                <div
                  className="flex items-center gap-2 px-1 h-full cursor-pointer hover:bg-gray-50 rounded-l-lg transition-colors"
                  onClick={() => setShowCountryDropdown(!showCountryDropdown)}
                >
                  <div className="flex items-center gap-1 shrink-0">
                    {selectedImage && (
                      <Image
                        src={`${BASE_URL}/uploads/${selectedImage}`}
                        alt="Country Flag"
                        width={16}
                        height={12}
                        className=" object-contain"
                      />
                    )}
                    <span className="text-[#1E222A] text-sm leading-none">
                      {signUpData.countryCode}
                    </span>
                    <ChevronDown className="w-4 h-4 text-gray-500" />
                  </div>
                </div>

                {showCountryDropdown && (
                  <div className="absolute z-50 top-full left-0 mt-1 bg-white rounded-lg shadow-lg border border-gray-200 max-h-60 overflow-y-auto w-44">
                    {countriesState?.map((country: any) => {
                      const displayCode = country.phonecode ? `+${country.phonecode}` : (country.countryCode || "");
                      const displayName = country.billcountry || country.countryName || "";
                      const flag = country.countryFlag || "";
                      
                      return (
                        <div
                          key={country._id}
                          className={`flex items-center gap-2 px-2 py-2 cursor-pointer hover:bg-gray-100 transition-colors ${
                            signUpData.countryCode === displayCode ? "bg-blue-50" : ""
                          }`}
                          onClick={() => selectCountry(country)}
                        >
                          {flag && (
                            <Image
                              src={`${BASE_URL}/uploads/${flag}`}
                              alt={displayName}
                              width={20}
                              height={14}
                              className="rounded-sm object-contain"
                            />
                          )}
                          <span className="text-sm text-gray-700">
                            {displayCode}
                          </span>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>

              <span className="h-5 w-px bg-gray-300" />

              <input
                disabled={customer?.loading || isSubmitting}
                type="tel"
                name="phone"
                value={signUpData.phone}
                onChange={inputChangeHandler}
                placeholder={labels.personalInfo.mobile_placeholder || ''}
                maxLength={12}
                className="w-full bg-transparent outline-none text-[#1E222A] text-sm px-3"
              />
            </div>
          </div>

          {/* Date of Birth */}
<div>
  <label className="text-[13px] text-[#1E222A]">
    {labels.personalInfo.dob || 'Date of Birth'} <span className="text-red-500">*</span>
  </label>
  <div className="relative">
    <input
      type="date"
      name="dateOfBirth"
      id="dob-input"
      value={signUpData.dateOfBirth}
      onChange={inputChangeHandler}
      disabled={customer?.loading || isSubmitting}
      max={new Date(new Date().setFullYear(new Date().getFullYear() - 18)).toISOString().split("T")[0]}
      className="w-full p-3 bg-[#F8FAFC] rounded-lg outline-none text-[#1E222A] text-sm pr-10"
    />
    <button
      type="button"
      onClick={() => {
        const dateInput = document.getElementById('dob-input');
        if (dateInput && dateInput.showPicker) {
          dateInput.showPicker();
        }
      }}
      className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 hover:text-gray-700"
      style={{ background: 'transparent', border: 'none', cursor: 'pointer', padding: 0 }}
    >
      <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
        <line x1="16" y1="2" x2="16" y2="6"></line>
        <line x1="8" y1="2" x2="8" y2="6"></line>
        <line x1="3" y1="10" x2="21" y2="10"></line>
      </svg>
    </button>
  </div>
</div>
        </div>

        {/* CAPTCHA */}
        <div>
          <label className="text-[13px] text-[#1E222A]">
            {labels.formButtons.captcha_label || 'Captcha'} <span className="text-red-500">*</span>
          </label>
          <div className="flex items-center gap-3 mt-1">
            <div className="flex gap-2 items-center">
              <div
                className="captcha-wrapper"
                dangerouslySetInnerHTML={{ __html: captchaData.svg }}
              />
            </div>

            <input
              type="text"
              name="captchaInput"
              value={captchaInput}
              onChange={(e) => setCaptchaInput(e.target.value)}
              placeholder={labels.formButtons.captcha_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}
              disabled={customer?.loading || isSubmitting}
              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>

        {/* Terms and Conditions */}
        <div className="flex items-center gap-2">
          <input
            type="checkbox"
            name="termsConditions"
            checked={signUpData.termsConditions}
            onChange={inputChangeHandler}
            disabled={customer?.loading || isSubmitting}
            className="w-4 h-4"
          />
          <span className="text-sm text-gray-700">
            {labels.formButtons.terms_text || 'I agree to the'}{" "}
            <Link
              href="/terms-and-conditions"
               target="_blank"
            rel="noopener noreferrer"
              className="text-[#0084a5] font-medium"
            >
              {labels.formButtons.terms_link || 'Terms and Conditions'}
            </Link>{" "}
            &{" "}
            <Link
              href="/privacy-policy"
               target="_blank"
            rel="noopener noreferrer"
              className="text-[#0084a5] font-medium"
            >
              {labels.formButtons.privacy_link || 'Privacy Policy'}
            </Link>
          </span>
        </div>

        {/* Submit Button */}
        <button
          type="submit"
          disabled={customer?.loading || !isFormValid || isSubmitting}
          className={`w-full py-1 mt-2 rounded-lg text-white font-medium text-sm ${
            customer?.loading || !isFormValid || isSubmitting
              ? "bg-gray-400 cursor-not-allowed"
              : "bg-[#0084a5] hover:bg-[#006a85] cursor-pointer"
          }`}
        >
          {customer?.loading || isSubmitting ? (
            <Loader size={20} className="animate-spin mx-auto" />
          ) : (
            labels.formButtons.submit_button || "Create Account"
          )}
        </button>

        {/* Login Link */}
        <p className="text-center text-sm text-[#1E222A]">
          Already Registered?{" "}
          <Link
            href="/login"
            className="text-[#0084a5] font-medium cursor-pointer"
          >
            Login Now
          </Link>
        </p>
      </form>

      {/* App Store Links */}
      <div className="flex gap-2.5 justify-center mt-2">
        {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={25}
              src={`${BASE_URL}/${store?.socialIcon}`}
              alt={store?.socialTitle || "Store"}
              className="rounded-md"
            />
          </Link>
        ))}
      </div>
    </div>
  );
}