'use client'

import Box from '@mui/material/Box'
import Grid from '@mui/material/Grid'
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 Typography from '@mui/material/Typography'
import { COUNTRIES } from './PhoneEntryField'
import type { AddressEntry } from './types'

export const ADDRESS_COUNTRIES = [...COUNTRIES]
  .sort((a, b) => a.name.localeCompare(b.name))
  .map(c => ({ code: c.code, name: c.name, flag: c.flag }))

export const PROVINCE_LISTS: Record<string, string[]> = {
  TH: [
    'Amnat Charoen','Ang Thong','Bangkok','Bueng Kan','Buri Ram','Chachoengsao',
    'Chai Nat','Chaiyaphum','Chanthaburi','Chiang Mai','Chiang Rai','Chon Buri',
    'Chumphon','Kalasin','Kamphaeng Phet','Kanchanaburi','Khon Kaen','Krabi',
    'Lampang','Lamphun','Loei','Lop Buri','Mae Hong Son','Maha Sarakham','Mukdahan',
    'Nakhon Nayok','Nakhon Pathom','Nakhon Phanom','Nakhon Ratchasima','Nakhon Sawan',
    'Nakhon Si Thammarat','Nan','Narathiwat','Nong Bua Lam Phu','Nong Khai',
    'Nonthaburi','Pathum Thani','Pattani','Phangnga','Phatthalung','Phayao',
    'Phetchabun','Phetchaburi','Phichit','Phitsanulok','Phra Nakhon Si Ayutthaya',
    'Phrae','Phuket','Prachin Buri','Prachuap Khiri Khan','Ranong','Ratchaburi',
    'Rayong','Roi Et','Sa Kaeo','Sakon Nakhon','Samut Prakan','Samut Sakhon',
    'Samut Songkhram','Sara Buri','Satun','Sing Buri','Sisaket','Songkhla','Sukhothai',
    'Suphan Buri','Surat Thani','Surin','Tak','Trang','Trat','Ubon Ratchathani',
    'Udon Thani','Uthai Thani','Uttaradit','Yala','Yasothon',
  ],
  US: [
    'Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut',
    'Delaware','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa',
    'Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan',
    'Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire',
    'New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio',
    'Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota',
    'Tennessee','Texas','Utah','Vermont','Virginia','Washington','West Virginia',
    'Wisconsin','Wyoming','District of Columbia',
  ],
  CA: [
    'Alberta','British Columbia','Manitoba','New Brunswick','Newfoundland and Labrador',
    'Northwest Territories','Nova Scotia','Nunavut','Ontario','Prince Edward Island',
    'Quebec','Saskatchewan','Yukon',
  ],
  AU: [
    'Australian Capital Territory','New South Wales','Northern Territory','Queensland',
    'South Australia','Tasmania','Victoria','Western Australia',
  ],
  GB: ['England','Northern Ireland','Scotland','Wales'],
  DE: [
    'Baden-Württemberg','Bavaria','Berlin','Brandenburg','Bremen','Hamburg','Hesse',
    'Lower Saxony','Mecklenburg-Vorpommern','North Rhine-Westphalia','Rhineland-Palatinate',
    'Saarland','Saxony','Saxony-Anhalt','Schleswig-Holstein','Thuringia',
  ],
  MY: [
    'Johor','Kedah','Kelantan','Kuala Lumpur','Labuan','Malacca','Negeri Sembilan',
    'Pahang','Penang','Perak','Perlis','Putrajaya','Sabah','Sarawak','Selangor',
    'Terengganu',
  ],
  IN: [
    'Andhra Pradesh','Arunachal Pradesh','Assam','Bihar','Chhattisgarh','Goa','Gujarat',
    'Haryana','Himachal Pradesh','Jharkhand','Karnataka','Kerala','Madhya Pradesh',
    'Maharashtra','Manipur','Meghalaya','Mizoram','Nagaland','Odisha','Punjab',
    'Rajasthan','Sikkim','Tamil Nadu','Telangana','Tripura','Uttar Pradesh','Uttarakhand',
    'West Bengal','Delhi',
  ],
  CN: [
    'Anhui','Beijing','Chongqing','Fujian','Gansu','Guangdong','Guangxi','Guizhou',
    'Hainan','Hebei','Heilongjiang','Henan','Hong Kong SAR','Hubei','Hunan',
    'Inner Mongolia','Jiangsu','Jiangxi','Jilin','Liaoning','Macau SAR','Ningxia',
    'Qinghai','Shaanxi','Shandong','Shanghai','Shanxi','Sichuan','Tianjin','Tibet',
    'Xinjiang','Yunnan','Zhejiang',
  ],
  NZ: [
    'Auckland','Bay of Plenty','Canterbury','Gisborne',"Hawke's Bay",'Manawatū-Whanganui',
    'Marlborough','Nelson','Northland','Otago','Southland','Taranaki','Tasman',
    'Waikato','Wellington','West Coast',
  ],
  FR: [
    'Auvergne-Rhône-Alpes','Bourgogne-Franche-Comté','Bretagne','Centre-Val de Loire',
    'Corse','Grand Est','Hauts-de-France','Île-de-France','Normandie',
    'Nouvelle-Aquitaine','Occitanie','Pays de la Loire',"Provence-Alpes-Côte d'Azur",
  ],
  JP: [
    'Aichi','Akita','Aomori','Chiba','Ehime','Fukui','Fukuoka','Fukushima','Gifu',
    'Gunma','Hiroshima','Hokkaido','Hyogo','Ibaraki','Ishikawa','Iwate','Kagawa',
    'Kagoshima','Kanagawa','Kochi','Kumamoto','Kyoto','Mie','Miyagi','Miyazaki',
    'Nagano','Nagasaki','Nara','Niigata','Oita','Okayama','Okinawa','Osaka','Saga',
    'Saitama','Shiga','Shimane','Shizuoka','Tochigi','Tokushima','Tokyo','Tottori',
    'Toyama','Wakayama','Yamagata','Yamaguchi','Yamanashi',
  ],
  KR: [
    'Busan','Chungcheongbuk-do','Chungcheongnam-do','Daegu','Daejeon','Gangwon-do',
    'Gwangju','Gyeonggi-do','Gyeongsangbuk-do','Gyeongsangnam-do','Incheon','Jeju',
    'Jeollabuk-do','Jeollanam-do','Sejong','Seoul','Ulsan',
  ],
}

const ADDRESS_TYPES: AddressEntry['type'][] = [
  'primary', 'mailing', 'billing', 'home', 'foreign', 'other',
]

const TYPE_LABELS: Record<AddressEntry['type'], string> = {
  primary: 'Primary',
  mailing: 'Mailing',
  billing: 'Billing',
  home: 'Home',
  foreign: 'Foreign Residence',
  other: 'Other',
}

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

export default function AddressEntryField({ entry, index, onChange, onRemove, canRemove }: Props) {
  const set = (field: keyof AddressEntry) => (e: React.ChangeEvent<HTMLInputElement>) =>
    onChange({ ...entry, [field]: e.target.value })

  const setCountry = (code: string) =>
    onChange({ ...entry, country: code, state: '' })

  const provinces = PROVINCE_LISTS[entry.country] ?? null
  const countryObj = ADDRESS_COUNTRIES.find(c => c.code === entry.country)

  const line1Error = !!(entry.city || entry.state || entry.postal) && !entry.line1

  return (
    <Box sx={{
      border: '1px solid', borderColor: 'divider', borderRadius: 1,
      p: 2, position: 'relative', bgcolor: index === 0 ? 'action.hover' : 'transparent',
    }}>
      {/* Header row: type + remove */}
      <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 1.5 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          {countryObj && <span style={{ fontSize: '1.1rem' }}>{countryObj.flag}</span>}
          <Typography variant='caption' sx={{ fontWeight: 600, color: 'text.secondary' }}>
            {index === 0 ? 'Primary Address' : `Address ${index + 1}`}
          </Typography>
        </Box>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <TextField select size='small' label='Type' value={entry.type}
            onChange={e => onChange({ ...entry, type: e.target.value as AddressEntry['type'] })}
            sx={{ width: 160 }}>
            {ADDRESS_TYPES.map(t => (
              <MenuItem key={t} value={t}>{TYPE_LABELS[t]}</MenuItem>
            ))}
          </TextField>
          {canRemove && (
            <Tooltip title='Remove address'>
              <IconButton size='small' onClick={onRemove}>
                <i className='ri-delete-bin-line' style={{ fontSize: '1rem', color: '#FF4C51' }} />
              </IconButton>
            </Tooltip>
          )}
        </Box>
      </Box>

      <Grid container spacing={1.5}>
        {/* Country first — affects province dropdown */}
        <Grid size={{ xs: 12, sm: 5 }}>
          <TextField fullWidth select size='small' label='Country'
            value={entry.country} onChange={e => setCountry(e.target.value)}>
            <MenuItem value=''><em>Select country</em></MenuItem>
            {ADDRESS_COUNTRIES.map(c => (
              <MenuItem key={c.code} value={c.code}>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <span>{c.flag}</span><span>{c.name}</span>
                </Box>
              </MenuItem>
            ))}
          </TextField>
        </Grid>

        {/* State/Province */}
        <Grid size={{ xs: 12, sm: 5 }}>
          {provinces ? (
            <TextField fullWidth select size='small' label='State / Province'
              value={entry.state} onChange={set('state')}>
              <MenuItem value=''><em>Select province</em></MenuItem>
              {provinces.map(p => <MenuItem key={p} value={p}>{p}</MenuItem>)}
            </TextField>
          ) : (
            <TextField fullWidth size='small' label='State / Province'
              value={entry.state} onChange={set('state')} />
          )}
        </Grid>

        {/* Postal code */}
        <Grid size={{ xs: 12, sm: 2 }}>
          <TextField fullWidth size='small' label='Postal Code'
            value={entry.postal} onChange={set('postal')}
            inputProps={{ inputMode: 'text' }} />
        </Grid>

        {/* Street */}
        <Grid size={{ xs: 12, sm: 8 }}>
          <TextField fullWidth size='small' label='Street Address'
            placeholder='House/unit number and street name'
            value={entry.line1} onChange={set('line1')}
            error={line1Error}
            helperText={line1Error ? 'Street address required' : undefined} />
        </Grid>

        {/* Suite/floor */}
        <Grid size={{ xs: 12, sm: 4 }}>
          <TextField fullWidth size='small' label='Suite / Floor / Building'
            placeholder='Optional'
            value={entry.line2} onChange={set('line2')} />
        </Grid>

        {/* City */}
        <Grid size={{ xs: 12, sm: 6 }}>
          <TextField fullWidth size='small' label='City / District'
            value={entry.city} onChange={set('city')} />
        </Grid>
      </Grid>
    </Box>
  )
}
