import {Grid, Typography, TextField, Box, InputLabel, Select, MenuItem, Avatar, SelectChangeEvent} from '@mui/material';
import axios from 'axios';
import { MuiTelInput, matchIsValidTel } from 'mui-tel-input'
import { useEffect, useState } from 'react';

interface Paises {

  name: {
    common: string;
  };

  flags: {
    svg: string;
  };

}

export const DadosPessoais = ( {formik}: any ) => {

  const [selectedValue, setSelectedValue] = useState('Portugal');

  const handleChange2 = (event: SelectChangeEvent<unknown>) => {
    setSelectedValue(event.target.value as string);
    formik.setFieldValue( 'pais', event.target.value);
  };
  
  const handleChange = (newValue: string) => {

    formik.setFieldValue('telemovelDP', newValue);
    
    const isValid = matchIsValidTel(newValue);

    if (!isValid) {
      formik.setFieldError('telemovelDP', 'Por favor insira um número de telemóvel válido');
    } else {
      formik.setFieldError('telemovelDP', '');
    }
  };

  const [countries, setCountries] = useState<Paises[]>([]);

  useEffect(() => {
    axios.get<Paises[]>('https://restcountries.com/v3.1/all?fields=name,flags')
      .then(response => {
        const sortedCountries = response.data.sort((a, b) => a.name.common.localeCompare(b.name.common));
        setCountries(sortedCountries);
      })
      .catch(error => {
        console.error('Error fetching countries:', error);
      });
  }, []);


  return (
    <Box>
      <Typography variant="h6" gutterBottom>
        Dados Pessoais
      </Typography>
      <Grid container spacing={3}>
        <Grid item xs={12} sm={6}>
          <TextField
            {...formik.getFieldProps('empresa')}
            required
            id="empresa"
            name="empresa"
            label="Nome/Empresa"
            fullWidth
            variant="standard"
            error={formik.touched.empresa && Boolean(formik.errors.empresa)}
            helperText={formik.touched.empresa && formik.errors.empresa}
          />
        </Grid>
        <Grid item xs={12} sm={6}>
          <TextField
            {...formik.getFieldProps('nif')}
            type='text'
            id="nif"
            name="nif"
            label="NIF/NIPC"
            fullWidth
            variant="standard"
          />
        </Grid>
        <Grid item xs={12} sm={12}>
          <TextField
            {...formik.getFieldProps('representante')}
            required
            type='text'
            id="representante"
            name="representante"
            label="Nome do representante legal (empresa)"
            fullWidth
            variant="standard"
            error={formik.touched.representante && Boolean(formik.errors.representante)}
            helperText={formik.touched.representante && formik.errors.representante}
          />
        </Grid>
        <Grid item xs={12} sm={6}>
          <MuiTelInput
            {...formik.getFieldProps('telemovelDP')}
            required
            id="telemovelDP"
            label="Telemóvel"
            value={formik.values.telemovelDP}
            fullWidth
            onChange={handleChange}
            variant="standard"
            defaultCountry="PT"
            error={formik.touched.telemovelDP && Boolean(formik.errors.telemovelDP)}
            helperText={formik.touched.telemovelDP && formik.errors.telemovelDP}
          />
        </Grid>
        <Grid item xs={12} sm={6}>
          <TextField
            {...formik.getFieldProps('emailDP')}
            required
            type='email'
            id="emailDP"
            name="emailDP"
            label="Email"
            fullWidth
            variant="standard"
            error={formik.touched.emailDP && Boolean(formik.errors.emailDP)}
            helperText={formik.touched.emailDP && formik.errors.emailDP}
          />
        </Grid>
        <Grid item xs={12} sm={6}>
          <TextField
            {...formik.getFieldProps('morada')}
            type='text'
            id="morada"
            name="morada"
            label="Morada"
            fullWidth
            variant="standard"
          />
        </Grid>
        <Grid item xs={12} sm={6}>
          <TextField
            {...formik.getFieldProps('andar')}
            type='text'
            id="andar"
            name="andar"
            label="Andar/Nº/Bloco"
            fullWidth
            variant="standard"
          />
        </Grid>
        <Grid item xs={12} sm={4}>
          <InputLabel id="pais-label">País</InputLabel>
          <Select
            {...formik.getFieldProps('pais')}
            labelId="pais-label"
            id="pais"
            name="pais"
            label="País"
            fullWidth
            variant="standard"
            value={selectedValue}
            onChange={ (e) => handleChange2 (e)}
          >
            {countries.map((country: Paises, index: number) => (
              <MenuItem key={index} value={country.name.common}>
                <Box sx={{ display: 'flex' }}>
                  <Avatar style={{ width: '30px', height: '20px', borderRadius: '5px', marginRight: '5px' }} src={country.flags.svg} alt={country.name.common} /> 
                  {country.name.common}
                </Box>
              </MenuItem>
            ))}
          </Select>
        </Grid>
        <Grid item xs={12} sm={4} sx={{ mt: 0.9 }}>
          <TextField
            {...formik.getFieldProps('cidade')}
            required
            type='text'
            id="cidade"
            name="cidade"
            label="Cidade"
            fullWidth
            variant="standard"
          />
        </Grid>
        <Grid item xs={12} sm={4} sx={{ mt: 0.9 }}>
          <TextField
            {...formik.getFieldProps('codigoPostal')}
            type='text'
            id="codigoPostal"
            name="codigoPostal"
            label="Código Postal"
            fullWidth
            variant="standard"
          />
        </Grid>
      </Grid>
    </Box>
  );
};
