'use client'

import Box from '@mui/material/Box'
import TextField from '@mui/material/TextField'
import MenuItem from '@mui/material/MenuItem'
import IconButton from '@mui/material/IconButton'
import Tooltip from '@mui/material/Tooltip'
import type { PhoneEntry } from './types'

// Common countries in Thai legal practice — full list subset
export const COUNTRIES: { code: string; name: string; dialCode: string; flag: string }[] = [
  { code: 'TH', name: 'Thailand',         dialCode: '+66',  flag: '🇹🇭' },
  { code: 'US', name: 'United States',    dialCode: '+1',   flag: '🇺🇸' },
  { code: 'GB', name: 'United Kingdom',   dialCode: '+44',  flag: '🇬🇧' },
  { code: 'AU', name: 'Australia',        dialCode: '+61',  flag: '🇦🇺' },
  { code: 'CN', name: 'China',            dialCode: '+86',  flag: '🇨🇳' },
  { code: 'JP', name: 'Japan',            dialCode: '+81',  flag: '🇯🇵' },
  { code: 'KR', name: 'South Korea',      dialCode: '+82',  flag: '🇰🇷' },
  { code: 'SG', name: 'Singapore',        dialCode: '+65',  flag: '🇸🇬' },
  { code: 'MY', name: 'Malaysia',         dialCode: '+60',  flag: '🇲🇾' },
  { code: 'IN', name: 'India',            dialCode: '+91',  flag: '🇮🇳' },
  { code: 'DE', name: 'Germany',          dialCode: '+49',  flag: '🇩🇪' },
  { code: 'FR', name: 'France',           dialCode: '+33',  flag: '🇫🇷' },
  { code: 'CA', name: 'Canada',           dialCode: '+1',   flag: '🇨🇦' },
  { code: 'NZ', name: 'New Zealand',      dialCode: '+64',  flag: '🇳🇿' },
  { code: 'HK', name: 'Hong Kong',        dialCode: '+852', flag: '🇭🇰' },
  { code: 'TW', name: 'Taiwan',           dialCode: '+886', flag: '🇹🇼' },
  { code: 'ID', name: 'Indonesia',        dialCode: '+62',  flag: '🇮🇩' },
  { code: 'PH', name: 'Philippines',      dialCode: '+63',  flag: '🇵🇭' },
  { code: 'VN', name: 'Vietnam',          dialCode: '+84',  flag: '🇻🇳' },
  { code: 'MM', name: 'Myanmar',          dialCode: '+95',  flag: '🇲🇲' },
  { code: 'RU', name: 'Russia',           dialCode: '+7',   flag: '🇷🇺' },
  { code: 'BR', name: 'Brazil',           dialCode: '+55',  flag: '🇧🇷' },
  { code: 'MX', name: 'Mexico',           dialCode: '+52',  flag: '🇲🇽' },
  { code: 'ZA', name: 'South Africa',     dialCode: '+27',  flag: '🇿🇦' },
  { code: 'AE', name: 'UAE',              dialCode: '+971', flag: '🇦🇪' },
  { code: 'IL', name: 'Israel',           dialCode: '+972', flag: '🇮🇱' },
  { code: 'CH', name: 'Switzerland',      dialCode: '+41',  flag: '🇨🇭' },
  { code: 'NL', name: 'Netherlands',      dialCode: '+31',  flag: '🇳🇱' },
  { code: 'SE', name: 'Sweden',           dialCode: '+46',  flag: '🇸🇪' },
  { code: 'IT', name: 'Italy',            dialCode: '+39',  flag: '🇮🇹' },
  { code: 'ES', name: 'Spain',            dialCode: '+34',  flag: '🇪🇸' },
]

const PHONE_TYPES: PhoneEntry['type'][] = ['mobile', 'office', 'whatsapp', 'line', 'signal', 'fax', 'other']

interface Props {
  entry: PhoneEntry
  onChange: (updated: PhoneEntry) => void
  onRemove: () => void
  canRemove: boolean
}

export default function PhoneEntryField({ entry, onChange, onRemove, canRemove }: Props) {
  const country = COUNTRIES.find(c => c.code === entry.countryCode) ?? COUNTRIES[0]

  const setField = (field: keyof PhoneEntry, value: string) =>
    onChange({ ...entry, [field]: value })

  const setCountry = (code: string) => {
    const c = COUNTRIES.find(x => x.code === code)!
    onChange({ ...entry, countryCode: code, dialCode: c.dialCode })
  }

  // Validate: digits, spaces, hyphens only; warn if too short/long
  const localDigits = entry.number.replace(/\D/g, '')
  const invalid = localDigits.length > 0 && (localDigits.length < 6 || localDigits.length > 13)

  return (
    <Box sx={{ display: 'flex', gap: 1, alignItems: 'flex-start' }}>
      {/* Country selector */}
      <TextField
        select size='small'
        value={entry.countryCode}
        onChange={e => setCountry(e.target.value)}
        sx={{ minWidth: 160 }}
        label='Country'
      >
        {COUNTRIES.map(c => (
          <MenuItem key={c.code} value={c.code}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <span style={{ fontSize: '1.1rem' }}>{c.flag}</span>
              <span style={{ fontSize: '0.8rem' }}>{c.dialCode}</span>
              <span style={{ fontSize: '0.75rem', color: '#9CA3AF' }}>{c.name}</span>
            </Box>
          </MenuItem>
        ))}
      </TextField>

      {/* Dial code display */}
      <TextField
        size='small'
        value={country.dialCode}
        disabled
        sx={{ width: 72 }}
        label='Code'
      />

      {/* Local number */}
      <TextField
        size='small'
        label='Number'
        value={entry.number}
        onChange={e => setField('number', e.target.value)}
        placeholder='81-999-0000'
        error={invalid}
        helperText={invalid ? 'Check number length' : undefined}
        sx={{ flex: 1 }}
        inputProps={{ inputMode: 'tel' }}
      />

      {/* Type */}
      <TextField
        select size='small'
        label='Type'
        value={entry.type}
        onChange={e => setField('type', e.target.value as PhoneEntry['type'])}
        sx={{ width: 120 }}
      >
        {PHONE_TYPES.map(t => (
          <MenuItem key={t} value={t} sx={{ textTransform: 'capitalize' }}>{t}</MenuItem>
        ))}
      </TextField>

      {/* Remove */}
      {canRemove && (
        <Tooltip title='Remove'>
          <IconButton size='small' onClick={onRemove} sx={{ mt: 0.5 }}>
            <i className='ri-delete-bin-line' style={{ fontSize: '1rem', color: '#FF4C51' }} />
          </IconButton>
        </Tooltip>
      )}
    </Box>
  )
}
