import {
  TextField,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  Box,
  Autocomplete,
  Grid,
  type SelectChangeEvent,
  FormHelperText,
} from '@mui/material';
import { useTranslation } from 'react-i18next';
import { Woman, Man } from 'iconsax-react';
import DateOfBirth from './DateOfBirth';
import { countries } from '@/data/countries';
import { Icon } from '@rkheftan/harmony-ui';
import { type PersonalInfoFieldsProps } from '../../types/settingForm';
import { Gender } from '../../types/settingForm';
import ReactCountryFlag from 'react-country-flag';
import { sanitizeLocalNumber } from '@/utils/regexes/sanitizeNumber';

export function PersonalInfoFields({
  firstName,
  setFirstName,
  lastName,
  setLastName,
  nationalId,
  setNationalId,
  birthDate,
  setBirthDate,
  sex,
  setSex,
  country,
  setCountry,
  errors,
  touched,
  handleBlur,
}: PersonalInfoFieldsProps) {
  const { t } = useTranslation(['completionForm', 'country']);

  const countryOptions = countries.map((c) => ({
    code: c.code,
    label: t(c.label, { ns: 'country' }),
  }));

  const currentCountry = countryOptions.find((c) => c.code === country) || null;

  const handleChangeSex = (e: SelectChangeEvent<Gender>) => {
    setSex(e.target.value as Gender);
  };

  const genderOptions = [
    {
      value: Gender.Female,
      icon: Woman,
      label: t('completion.woman'),
      color: '#F50057',
    },
    {
      value: Gender.Male,
      icon: Man,
      label: t('completion.man'),
      color: '#0091EA',
    },
  ];

  return (
    <Grid container spacing={2}>
      <Grid size={{ xs: 12, md: 6 }}>
        <TextField
          autoFocus
          fullWidth
          label={t('completion.name')}
          placeholder={t('completion.name')}
          variant="outlined"
          value={firstName}
          onChange={(e) => setFirstName(e.target.value)}
          onBlur={() => handleBlur('firstName')}
          error={touched.firstName && !!errors.firstName}
          helperText={touched.firstName && errors.firstName}
        />
      </Grid>

      <Grid size={{ xs: 12, md: 6 }}>
        <TextField
          fullWidth
          label={t('completion.familyName')}
          placeholder={t('completion.familyName')}
          variant="outlined"
          value={lastName}
          onChange={(e) => setLastName(e.target.value)}
          onBlur={() => handleBlur('lastName')}
          error={touched.lastName && !!errors.lastName}
          helperText={touched.lastName && errors.lastName}
        />
      </Grid>

      <Grid size={{ xs: 12, md: 6 }}>
        <FormControl fullWidth error={touched.sex && !!errors.sex}>
          <InputLabel>{t('completion.gender')}</InputLabel>
          <Select
            value={sex || ''}
            label={t('completion.gender')}
            onChange={handleChangeSex}
            onBlur={() => handleBlur('sex')}
          >
            {genderOptions.map((g) => (
              <MenuItem key={g.value} value={g.value}>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Icon Component={g.icon} size="small" color={g.color} />
                  {g.label}
                </Box>
              </MenuItem>
            ))}
          </Select>

          {touched.sex && errors.sex && (
            <FormHelperText>{errors.sex}</FormHelperText>
          )}
        </FormControl>
      </Grid>

      <Grid size={{ xs: 12, md: 6 }}>
        <Autocomplete
          fullWidth
          options={countryOptions}
          getOptionLabel={(option) => option.label}
          noOptionsText={t('completion.noOption')}
          value={currentCountry}
          onChange={(_, newValue) => setCountry(newValue?.code || '')}
          onBlur={() => handleBlur('country')}
          autoFocus
          renderOption={(props, option) => (
            <Box component="li" {...props} key={option.code}>
              <ReactCountryFlag
                countryCode={option.code}
                svg
                style={{
                  height: '1.5rem',
                  width: '1.5rem',
                  marginTop: '-2px',
                  marginRight: '4px',
                  marginLeft: '8px',
                }}
              />
              {option.label}
            </Box>
          )}
          renderInput={(params) => (
            <TextField
              {...params}
              label={t('completion.country')}
              error={touched.country && !!errors.country}
              helperText={touched.country && errors.country}
            />
          )}
          clearOnEscape
        />
      </Grid>

      <Grid size={{ xs: 12, md: 6 }}>
        <TextField
          fullWidth
          label={t('completion.optionalNationalCode')}
          placeholder={t('completion.optionalNationalCode')}
          value={nationalId}
          onChange={(e) => {
            const normalized = sanitizeLocalNumber(e.target.value);

            if (normalized.length <= 10) {
              setNationalId(normalized);
            }
          }}
          variant="outlined"
          onBlur={() => handleBlur('nationalId')}
          error={touched.nationalId && !!errors.nationalId}
          helperText={touched.nationalId && errors.nationalId}
        />
      </Grid>

      <Grid size={{ xs: 12, md: 6 }}>
        <DateOfBirth value={birthDate} onChange={setBirthDate} />
      </Grid>
    </Grid>
  );
}
