"use client";

import PhoneInput, { type Country } from 'react-phone-number-input';
import 'react-phone-number-input/style.css';
import { cn } from '@/lib/utils';
import { useGeoCountry } from '@/lib/useGeoCountry';
import type { FormTheme } from './Field';

type Props = {
  id?: string;
  value: string | undefined;
  onChange: (value: string | undefined) => void;
  onBlur?: () => void;
  theme?: FormTheme;
};

/**
 * Champ téléphone international : sélecteur de pays (drapeau + indicatif) + validation
 * (gérée côté schéma via isValidPhoneNumber). Valeur stockée au format E.164 (ex: +33612345678).
 * Pays par défaut déduit de l'IP via /api/geo (en-tête Vercel), fallback FR — mutualisé avec le pays.
 */
export const PhoneField = ({ id, value, onChange, onBlur, theme = 'light' }: Props) => {
  const country = useGeoCountry('FR');
  const dark = theme === 'dark';

  return (
    <div className={cn(
      'w-full px-4 py-3 rounded-xl border-2 focus-within:border-primary transition-colors',
      dark ? 'bg-white/[0.07] border-white/[0.12]' : 'bg-white border-foreground/10',
    )}>
      <PhoneInput
        // Remonte le composant quand le pays géo-IP est résolu (la valeur, contrôlée, est conservée).
        key={country}
        id={id}
        international
        defaultCountry={country as Country}
        value={value}
        onChange={onChange}
        onBlur={onBlur}
        countryCallingCodeEditable={false}
        // `text-white` en sombre : la flèche du sélecteur de pays utilise currentColor.
        className={cn('flex items-center gap-2', dark && 'text-white')}
        numberInputProps={{
          className: cn(
            'flex-1 min-w-0 bg-transparent outline-none border-0 p-0 text-base',
            dark ? 'text-white placeholder:text-white/30' : 'text-foreground placeholder:text-foreground/30',
          ),
        }}
      />
    </div>
  );
};
