import { useState, useRef, useEffect } from 'react';

const COUNTRIES = [
  { code: '+1', flag: '🇺🇸', name: 'United States', format: '(XXX) XXX-XXXX', maxDigits: 10 },
  { code: '+61', flag: '🇦🇺', name: 'Australia', format: 'XXXX XXX XXX', maxDigits: 10 },
  { code: '+44', flag: '🇬🇧', name: 'United Kingdom', format: 'XXXX XXXXXX', maxDigits: 10 },
  { code: '+62', flag: '🇮🇩', name: 'Indonesia', format: 'XXX-XXXX-XXXX', maxDigits: 12 },
  { code: '+81', flag: '🇯🇵', name: 'Japan', format: 'XX-XXXX-XXXX', maxDigits: 10 },
  { code: '+82', flag: '🇰🇷', name: 'South Korea', format: 'XX-XXXX-XXXX', maxDigits: 10 },
  { code: '+86', flag: '🇨🇳', name: 'China', format: 'XXX XXXX XXXX', maxDigits: 11 },
  { code: '+91', flag: '🇮🇳', name: 'India', format: 'XXXXX XXXXX', maxDigits: 10 },
  { code: '+33', flag: '🇫🇷', name: 'France', format: 'X XX XX XX XX', maxDigits: 9 },
  { code: '+49', flag: '🇩🇪', name: 'Germany', format: 'XXXX XXXXXXX', maxDigits: 11 },
  { code: '+55', flag: '🇧🇷', name: 'Brazil', format: 'XX XXXXX-XXXX', maxDigits: 11 },
  { code: '+52', flag: '🇲🇽', name: 'Mexico', format: 'XX XXXX XXXX', maxDigits: 10 },
  { code: '+65', flag: '🇸🇬', name: 'Singapore', format: 'XXXX XXXX', maxDigits: 8 },
  { code: '+60', flag: '🇲🇾', name: 'Malaysia', format: 'XX-XXXX XXXX', maxDigits: 10 },
  { code: '+66', flag: '🇹🇭', name: 'Thailand', format: 'XX XXX XXXX', maxDigits: 9 },
  { code: '+971', flag: '🇦🇪', name: 'UAE', format: 'XX XXX XXXX', maxDigits: 9 },
  { code: '+966', flag: '🇸🇦', name: 'Saudi Arabia', format: 'XX XXX XXXX', maxDigits: 9 },
];

function parsePhone(fullPhone) {
  if (!fullPhone) return { countryCode: '+1', number: '' };
  const match = COUNTRIES.find((c) => fullPhone.startsWith(c.code));
  if (match) {
    return { countryCode: match.code, number: fullPhone.slice(match.code.length).trim() };
  }
  return { countryCode: '+1', number: fullPhone.replace(/^\+\d{1,3}\s?/, '') };
}

function formatNumber(digits, country) {
  if (!country) return digits;
  const f = country.format;
  let result = '';
  let di = 0;
  for (let i = 0; i < f.length && di < digits.length; i++) {
    if (f[i] === 'X') {
      result += digits[di++];
    } else {
      result += f[i];
    }
  }
  return result;
}

export function validatePhone(fullPhone) {
  if (!fullPhone) return 'Phone number is required';
  const { countryCode, number } = parsePhone(fullPhone);
  const country = COUNTRIES.find((c) => c.code === countryCode);
  const digits = number.replace(/\D/g, '');
  if (!country) return 'Invalid country code';
  if (digits.length < country.maxDigits - 2) return `Too short for ${country.name} (need ${country.maxDigits} digits)`;
  if (digits.length > country.maxDigits) return `Too long for ${country.name} (max ${country.maxDigits} digits)`;
  return null;
}

export default function PhoneInput({ value, onChange }) {
  const { countryCode, number } = parsePhone(value);
  const [cc, setCc] = useState(countryCode);
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  const country = COUNTRIES.find((c) => c.code === cc);

  // Close dropdown on outside click
  useEffect(() => {
    const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  const handleCountryChange = (newCc) => {
    setCc(newCc);
    setOpen(false);
    onChange('');
  };

  const handleNumberChange = (raw) => {
    const digits = raw.replace(/\D/g, '');
    const limited = country ? digits.slice(0, country.maxDigits) : digits;
    const formatted = formatNumber(limited, country);
    onChange(limited ? `${cc} ${formatted}` : '');
  };

  const displayNumber = (() => {
    const digits = number.replace(/\D/g, '');
    return formatNumber(digits, country);
  })();

  const selected = COUNTRIES.find((c) => c.code === cc);

  return (
    <div className="flex gap-1 relative" ref={ref}>
      {/* Country selector button */}
      <button
        type="button"
        className="bg-s2 border border-bd rounded-md text-t1 text-[13px] px-2 py-1.5 flex items-center gap-1 flex-shrink-0 hover:bg-bd/30 transition-colors"
        onClick={() => setOpen(!open)}
      >
        <span className="text-base leading-none">{selected?.flag}</span>
        <span className="text-[11px] text-t2">{selected?.code}</span>
        <span className="text-[9px] text-t3 ml-0.5">▼</span>
      </button>

      {/* Dropdown */}
      {open && (
        <div className="absolute top-full left-0 mt-1 bg-s1 border border-bd rounded-md shadow-lg z-50 w-[260px] max-h-[240px] overflow-auto">
          {COUNTRIES.map((c) => (
            <div
              key={c.code}
              className={`flex items-center gap-2.5 px-3 py-2 cursor-pointer text-[12px] transition-colors ${
                c.code === cc ? 'bg-ac/15 text-ac' : 'text-t1 hover:bg-s2'
              }`}
              onClick={() => handleCountryChange(c.code)}
            >
              <span className="text-base leading-none">{c.flag}</span>
              <span className="flex-1">{c.name}</span>
              <span className="text-t2 text-[11px]">{c.code}</span>
            </div>
          ))}
        </div>
      )}

      {/* Phone number input */}
      <input
        className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]"
        value={displayNumber}
        onChange={(e) => handleNumberChange(e.target.value)}
        placeholder={country?.format || 'Phone number'}
      />
    </div>
  );
}
