import React, { useEffect, useState } from 'react';
import {
  Box,
  InputAdornment,
  IconButton,
  Popover,
  SelectChangeEvent,
  RadioGroup,
  Typography,
  Radio,
  Autocomplete,
  FormControlLabel,
  Paper,
  useTheme,
  FormHelperText,
  Button,
  Checkbox,
} from '@mui/material';
import { faPalette, faClose, faEyeSlash, faEye, faFileArrowUp } from '@fortawesome/free-solid-svg-icons';
import SvgColor from '@/shared/components/svg-color';
import {
  StyledDatePicker,
  StyledFormControl,
  StyledSelect,
  StyledTextField,
  StyledInputLabel,
  StyledMenuItem,
} from '@/shared/theme/css';
import FontAwesome from '../fontawesome';
import { FormFieldType } from '@/shared/types/common';
import { IAvenant, ICircuit, ICircuitContract, IPreparationCircuit } from '@/shared/types/circuit';
import { ContractRequest, IContrat } from '@/shared/types/contract';
import { IChauffeur, Interval } from '@/shared/types/chauffeur';
import { IAddPoint, ITrajet } from '@/shared/types/trajet';
import { IAvenantUsager, IUsager } from '@/shared/types/usager';
import { IAbsence } from '@/shared/types/absence';
import { IClient } from '@/shared/types/client';
import {
  IAttendanceSheet,
  IEtablissement,
  IResponsableEtablissement,
} from '@/shared/types/etablissement';
import { IFileImport, IVacance } from '@/shared/types/vacance';
import { IDriverType, IPreparationDriver } from '@/shared/types/driver';
import { pxToRem } from '@/shared/theme/typography';
import { useResponsive } from '@/hooks';
import { IDriverAbsence } from '@/shared/types/driver-absence';
import { IBesoinRecrutement } from '@/shared/types/besoin-recrutement';
import { ICandidature, IFormulaire } from '@/shared/types/candidature';
import { Candidat } from '@/shared/types/candidat';
import { IDemandeAbsence, ILeave } from '@/shared/types/leave';
import { IPreparationUsager } from '@/shared/types/usager';
import { IRHAbsence } from '@/shared/types/absence-rh';
import { IAppointment } from '@/shared/types/appointment';
import { CalendarEvent } from '@/shared/sections/rh/calendar/types/calendar-types';
import { IRepresentative } from '@/shared/types/usager';
import { Document } from '@/shared/types/document';
import { DepartmentRequest, IAgency, IDepartment, ISector, Lot, LotRequest, SectorList, SectorRequest } from '@/shared/types/infrastructure';
import { IDemande } from '@/shared/types/demande';
import { IDocument, ISuiviDocument } from '@/shared/types/document';
import { IVehicle, IVehicleModel, IVehicleType } from '@/shared/types/flottes/vehicule';
import { IIntervention, ITypeReparation } from '@/shared/types/flottes/intervention';
import { IIncident, ITypeIncident } from '@/shared/types/flottes/incident';
import { IAgent } from '@/shared/types/agent';
import { IRole } from '@/shared/types/role';
import { IEquipe, TeamRequest } from '@/shared/types/equipe';
import { ModuleFormData } from '@/shared/types/ModuleFormData';
import { IMileage } from '@/shared/types/flottes/mileage';
import { InterventionFormData } from '@/shared/sections/planning/types/intervention-form';
import { IVehicleAffectation } from '@/shared/types/flottes/vehicle-affectation';
import { IFuelFee } from '@/shared/types/flottes/fuelFee';
import { IFuelHistory, IFuelImport, ITankerType } from '@/shared/types/flottes/fuelImport';
import { ILanguageSettings } from '@/shared/types/ILanguageSettings';
import { IPassword } from '@/shared/types/password';
import ConditionalComponent from '../table/ConditionalComponent';
import AddressMapSelector from '../google-maps/AddressMapSelector';
import { INotification } from '@/shared/types/notification';
import { AgencyRequest } from '@/shared/types/infrastructure';
import { EstablishmentRequest, EstablishmentResponsible } from '@/shared/types/establishment';
import { IRoadMapMileage } from '@/shared/types/driver-roadmap';
import { IPassengerList } from '@/shared/types/passenger';
import { AttendanceSheet } from '@/shared/types/attendance-sheet';

interface FormFieldProps {
  field:
  | FormFieldType<ICircuit & ICircuitContract>
  | FormFieldType<IContrat>
  | FormFieldType<ContractRequest>
  | FormFieldType<ICircuitContract>
  | FormFieldType<IChauffeur>
  | FormFieldType<ITrajet>
  | FormFieldType<IPassengerList>
  | FormFieldType<IAvenant>
  | FormFieldType<IAvenantUsager>
  | FormFieldType<IAbsence>
  | FormFieldType<IClient>
  | FormFieldType<IEtablissement>
  | FormFieldType<IResponsableEtablissement>
  | FormFieldType<EstablishmentRequest>
  | FormFieldType<EstablishmentResponsible>
  | FormFieldType<IVacance>
  | FormFieldType<IAttendanceSheet>
  | FormFieldType<IDriverType>
  | FormFieldType<IRepresentative>
  | FormFieldType<IPreparationUsager>
  | FormFieldType<IPreparationCircuit>
  | FormFieldType<IPreparationDriver>
  | FormFieldType<IDriverAbsence>
  | FormFieldType<Candidat>
  | FormFieldType<ILeave>
  | FormFieldType<IDemandeAbsence>
  | FormFieldType<IDemande>
  | FormFieldType<IDocument>
  | FormFieldType<ISuiviDocument>
  | FormFieldType<IAppointment>
  | FormFieldType<ICandidature>
  | FormFieldType<IAddPoint>
  | FormFieldType<IBesoinRecrutement>
  | FormFieldType<IFileImport>
  | FormFieldType<IFormulaire>
  | FormFieldType<IDocument>
  | FormFieldType<ISuiviDocument>
  | FormFieldType<IDemande>
  | FormFieldType<IRHAbsence>
  | FormFieldType<CalendarEvent>
  | FormFieldType<IAgency>
  | FormFieldType<AgencyRequest>
  | FormFieldType<IDepartment>
  | FormFieldType<DepartmentRequest>
  | FormFieldType<Lot>
  | FormFieldType<LotRequest>
  | FormFieldType<ISector>
  | FormFieldType<SectorList>
  | FormFieldType<SectorRequest>
  | FormFieldType<IVehicle>
  | FormFieldType<IIncident>
  | FormFieldType<IIntervention>
  | FormFieldType<IMileage>
  | FormFieldType<Document>
  | FormFieldType<IAgent>
  | FormFieldType<IRole>
  | FormFieldType<IEquipe>
  | FormFieldType<ModuleFormData>
  | FormFieldType<InterventionFormData>
  | FormFieldType<IVehicleAffectation>
  | FormFieldType<IFuelFee>
  | FormFieldType<IFuelHistory>
  | FormFieldType<ITypeIncident>
  | FormFieldType<ITypeReparation>
  | FormFieldType<IVehicleModel>
  | FormFieldType<IVehicleType>
  | FormFieldType<ITankerType>
  | FormFieldType<IFuelImport>
  | FormFieldType<IPassword>
  | FormFieldType<INotification>
  | FormFieldType<IRoadMapMileage>
  | FormFieldType<TeamRequest>
  | FormFieldType<ILanguageSettings>;

  value: any;
  formData?: any;
  openPopover?: (event: React.MouseEvent<HTMLElement>) => void;
  onChange: (name: string, value: any) => void;
  isReadOnly: boolean;
  disabled?: boolean;
  isDrawerElement?: boolean;
  sx?: any;
  error?: string;
  onBlur?: (e: React.FocusEvent) => void;
}
export const CustomDateIcon = ({ isReadOnly }: { isReadOnly?: boolean }) => (
  <SvgColor
    src="/assets/icons/ic_date.svg"
    sx={{
      color: isReadOnly ? 'text.disabled' : 'primary.main',
      width: 18,
      mr: '6px',
    }}
  />
);

function resolveRequired(
  required: boolean | ((values: any) => boolean) | undefined,
  formData?: any
): boolean {
  if (typeof required === 'function' && formData) {
    return required(formData);
  }
  return !!required;
}

export default function FormField({
  openPopover,
  field,
  value,
  onChange,
  isReadOnly,
  isDrawerElement,
  formData,
  error,
  onBlur,
}: FormFieldProps) {
  const [anchorEl, setAnchorEl] = useState<HTMLButtonElement | null>(null);
  const [showPassword, setShowPassword] = useState(false);
  const isBetweenSmAndLg = useResponsive('between', 'sm', 'lg');
  const theme = useTheme();
  const isSmallScreen = isBetweenSmAndLg || isDrawerElement;

  if (field.showWhen && !field.showWhen(formData)) {
    return null;
  }

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    onChange(field.name, e.target.value);
  };

  const handleSelectChange = (event: SelectChangeEvent<unknown>) => {
    if (field.name === 'trajet') {
      const selectedValue = event.target.value as string;
      const [depart, arriver] = selectedValue.split('-');
      onChange(field.name, { depart, arriver });
    } else {
      onChange(field.name, event.target.value as string);
    }
  };

  const getSelectValue = () => {
    if (field.name === 'trajet' && typeof value !== 'string') {
      return `${(value as Interval).depart || ''}-${(value as Interval).arriver || ''}`;
    }
    return (value as string) || '';
  };
  const fieldValue = value === null || value === undefined ? '' : value;

  const isRequired = resolveRequired(field.required, formData);

  switch (field.type) {
    case 'date':
      const dateValue = value ? new Date(value) : null;

      return (
        <Box sx={{ width: '100%' }}>
          <StyledDatePicker
            isSmallScreen={isSmallScreen}
            label={
              <>
                {field.label}
                {isRequired ? <span style={{ color: '#FF0000' }}> *</span> : <></>}
              </>
            }
            views={['year', 'month', 'day']}
            slots={{
              openPickerIcon: () => <CustomDateIcon isReadOnly={isReadOnly} />,
            }}
            openTo="year"
            readOnly={isReadOnly}
            value={dateValue}
            onChange={(newDate) => {
              const dateString = newDate?.toISOString() || '';
              onChange(field.name, dateString);
            }}
            onError={(reason, value) => {
              console.warn('Date validation error:', {
                reason,
                value,
                field: field.name,
              });
            }}
            slotProps={{
              textField: (params) => ({
                ...params,
                fullWidth: true,
                placeholder: 'DD/MM/YYYY',
                InputLabelProps: {
                  shrink: true,
                },
                error: !!error,
                helperText: error,
                onBlur: (e) => {
                  const isoDate = dateValue?.toISOString();
                  onChange(field.name, isoDate || '');
                  if (onBlur) onBlur(e);
                },
              }),
              actionBar: {
                actions: ['clear', 'today'],
              },
            }}
            sx={{
              ...(!!error && {
                '& .MuiOutlinedInput-root': {
                  borderColor: theme.palette.error.main + '!important',
                },
              }),
            }}
          />
        </Box>
      );
    case 'select':
    case 'multiple':
      return (
        <StyledFormControl fullWidth error={!!error}>
          <StyledInputLabel id={field.name}>
            {field.label}
            {isRequired ? <span style={{ color: '#FF0000' }}> *</span> : <></>}
          </StyledInputLabel>
          <StyledSelect
            sx={{
              fontSize: isSmallScreen ? pxToRem(13) : undefined,
            }}
            name={field.name}
            required={isRequired}
            labelId={field.name}
            value={getSelectValue()}
            onBlur={onBlur}
            onChange={handleSelectChange}
            disabled={isReadOnly}
            MenuProps={{
              PaperProps: {
                style: {
                  maxHeight: 300,
                },
              },
            }}
            isReadOnly={isReadOnly}
            multiple={field.type === 'multiple'}
            displayEmpty
            renderValue={(selected) => {
              if (selected === '' || (field.type === 'multiple' && (selected as string[]).length < 1)) {
                return (
                  <Typography
                    sx={{ color: '#A2A6AB', fontSize: isSmallScreen ? pxToRem(13) : undefined }}
                  >
                    {field.placeholder || 'Sélectionnez une option'}
                  </Typography>
                );
              }

              return field.type === 'multiple'
  ? field.name === 'collaborators'
    ? (selected as string[]).map(val => {
        const option = field.options?.find(opt => opt.value === val);
        return option ? option.label : val;
      }).join(', ')
    : field.name === 'usagers' && (selected as string[]).length > 1
      ? (selected as string[]).length.toString()
      : (selected as string[]).join(', ')
  : field.options?.find((option) => option.value === selected)?.label || '';
              }}
          >
            {field.options?.map((option) => (
              <StyledMenuItem key={option.value} value={option.value}>
                {option.label}
              </StyledMenuItem>
            ))}
          </StyledSelect>
          {error ? <FormHelperText sx={{ color: 'error.main' }}>{error}</FormHelperText> : <></>}
        </StyledFormControl>
      );
    case 'password':
      return (
        <StyledTextField
          type={showPassword ? 'text' : 'password'}
          label={field.label}
          name={field.name}
          value={fieldValue}
          error={!!error}
          helperText={error || ' '}
          onChange={(e) => onChange(field.name, e.target.value)}
          fullWidth
          sx={{
            '& .MuiFormHelperText-root': {
              visibility: error ? 'visible' : 'hidden',
              height: error ? 'auto' : '0px',
            },
          }}
          required={isRequired}
          onBlur={onBlur}
          disabled={isReadOnly}
          InputProps={{
            startAdornment: field.icon ? (
              <InputAdornment position="start">
                <FontAwesome icon={field.icon} sx={{ color: 'text.disabled' }} />
              </InputAdornment>
            ) : (
              <></>
            ),
            endAdornment: field.showPassword ? (
              <InputAdornment position="end">
                <IconButton
                  onClick={() => setShowPassword((prev) => !prev)}
                  edge="end"
                  disabled={false}
                  aria-label={showPassword ? 'Masquer le mot de passe' : 'Afficher le mot de passe'}
                >
                  <FontAwesome icon={showPassword ? faEyeSlash : faEye} />
                </IconButton>
              </InputAdornment>
            ) : (
              <></>
            ),
          }}
        />
      );
    case 'time':
      return (
        <StyledTextField
          isSmallScreen={isSmallScreen}
          fullWidth
          required={isRequired}
          name={field.name}
          type="time"
          value={value || ''}
          onChange={handleInputChange}
          label={field.label}
          InputLabelProps={{
            shrink: true,
          }}
          placeholder={field.placeholder || 'HH:mm'}
          InputProps={{
            readOnly: isReadOnly,
            endAdornment: field.icon ? (
              <InputAdornment position="end">
                <FontAwesome
                  icon={field.icon}
                  width={isSmallScreen ? 16 : 20}
                  color="primary.main"
                />
              </InputAdornment>
            ) : (
              <></>
            ),
          }}
          sx={{
            '& .MuiInputBase-root': {
              height: '56px',
              borderRadius: '8px',
              backgroundColor: 'background.paper',
              border: '2px solid #7635dc',
              '&:hover': {
                borderColor: '#7635dc',
              },
              '& fieldset': {
                border: 'none',
              },
              '& input[type="time"]::-webkit-calendar-picker-indicator': {
                display: 'none',
              },
              '& input[type="time"]::-webkit-inner-spin-button': {
                display: 'none',
              },
            },
          }}
        />
      );
    case 'checkbox':
      return (
        <Box display="flex" alignItems="center" gap={isSmallScreen ? 2 : 4}>
          <Typography
            sx={{
              fontSize: isSmallScreen ? pxToRem(13) : undefined,
              color: isReadOnly ? 'text.disabled' : 'primary.main',
            }}
          >
            {field.label}
          </Typography>

          <RadioGroup
            row
            name={field.name}
            value={String(value)}    
            onChange={handleInputChange}
            onBlur={onBlur}
            sx={{ cursor: isReadOnly ? 'not-allowed' : 'auto' }}
          >
            {field.options?.map((option) => (
              <FormControlLabel
                key={option.value}
                value={String(option.value)}   
                             control={
                  <Radio
                    sx={{
                      '& .MuiSvgIcon-root': {
                        fontSize: isSmallScreen ? pxToRem(18) : undefined,
                      },
                    }}
                  />
                }
                label={option.label}
                disabled={isReadOnly}
                sx={{
                  '& .MuiFormControlLabel-label': {
                    color: value === option.value ? 'primary.main' : 'inherit',
                    fontSize: isSmallScreen ? pxToRem(13) : undefined,
                  },
                }}
              />
            ))}
          </RadioGroup>
          {error ? <FormHelperText sx={{ color: 'error.main' }}>{error}</FormHelperText> : <></>}

        </Box>
      );
      case 'checkbox-group':
        return (
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            <Typography
              sx={{
                fontSize: isSmallScreen ? pxToRem(13) : undefined,
                color: isReadOnly ? 'text.disabled' : 'primary.main',
                minWidth: '140px'
              }}
            >
              {field.label}
              <ConditionalComponent
                isValid={isRequired}
                defaultComponent={null}
              >
                <span style={{ color: '#FF0000' }}> *</span>
              </ConditionalComponent>
            </Typography>
      
            <Box sx={{ 
              display: 'flex', 
              gap: 3,
              alignItems: 'center',
              flex: 1
            }}>
              {field.options?.map((option) => (
                <FormControlLabel
                  key={option.value}
                  control={
                    <Checkbox
                      checked={Array.isArray(value) ? value.includes(option.value) : value === option.value}
                      onChange={(e) => {
                        const newValue = Array.isArray(value) ? [...value] : [];
                        if (e.target.checked) {
                          newValue.push(option.value);
                        } else {
                          const index = newValue.indexOf(option.value);
                          if (index > -1) {
                            newValue.splice(index, 1);
                          }
                        }
                        onChange(field.name, newValue);
                      }}
                      disabled={isReadOnly}
                      sx={{
                        color: theme.palette.primary.main,
                        '&.Mui-checked': {
                          color: theme.palette.primary.main,
                        },
                        '& .MuiSvgIcon-root': {
                          fontSize: isSmallScreen ? pxToRem(18) : undefined,
                        },
                      }}
                    />
                  }
                  label={
                    <Typography 
                      sx={{ 
                        fontSize: isSmallScreen ? pxToRem(13) : undefined,
                        color: isReadOnly ? 'text.disabled' : 'text.primary'
                      }}
                    >
                      {option.label}
                    </Typography>
                  }
                  sx={{
                    margin: 0
                  }}
                />
              ))}
            </Box>
      
            <ConditionalComponent
              isValid={!!error}
              defaultComponent={null}
            >
              <FormHelperText error sx={{ mt: 0.5 }}>
                {error}
              </FormHelperText>
            </ConditionalComponent>
          </Box>
        );
      
    case 'color':
      return (
        <>
          <StyledTextField
            isSmallScreen={isSmallScreen}
            fullWidth
            error={!!error}
            helperText={error || ''}
            onBlur={onBlur}
            name={field.name}
            value={value}
            onChange={handleInputChange}
            label={field.label}
            sx={{
              ...(isReadOnly && {
                '& .MuiInputBase-root': {
                  backgroundColor: '#f5f5f5',
                  cursor: 'not-allowed',
                },
                '& .MuiInputBase-input': {
                  cursor: 'not-allowed',
                  color: 'text.disabled',
                },
              }),
            }}
            InputLabelProps={{
              shrink: true,
            }}
            placeholder={field.placeholder}
            InputProps={{
              readOnly: isReadOnly,
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton
                    disabled={isReadOnly}
                    onClick={(e) => setAnchorEl(e.currentTarget)}
                    sx={{ pr: 0 }}
                  >
                    <FontAwesome
                      icon={faPalette}
                      width={20}
                      color={isReadOnly ? 'text.disabled' : 'primary.main'}
                    />
                  </IconButton>
                </InputAdornment>
              ),
            }}
          />
          <Popover
            open={Boolean(anchorEl)}
            anchorEl={anchorEl}
            onClose={() => setAnchorEl(null)}
            anchorOrigin={{
              vertical: 'bottom',
              horizontal: 'left',
            }}
          >
            <Box p={2}>
              <input
                type="color"
                value={value}
                disabled={isReadOnly}
                onChange={(e) => onChange(field.name, e.target.value)}
                style={{ width: '200px', height: '50px' }}
              />
            </Box>
          </Popover>
        </>
      );
    case 'combobox':
      const options = field.options || [];
      return (
        <Autocomplete
          options={options}
          value={
            value
              ? options.find((opt) => opt.value === value) || {
                label: value.toString(),
                value: value.toString(),
              }
              : null
          }
          disabled={isReadOnly}
          onChange={(event, newValue) => {
            if (typeof newValue === 'string') {
              onChange(field.name, newValue);
            } else if (newValue) {
              const optionValue = newValue as any;
              if (optionValue.value !== undefined) {
                onChange(field.name, optionValue.value);
              } else {
                onChange(field.name, '');
              }
            } else {
              onChange(field.name, '');
            }
          }}
          renderOption={(props, option, { selected }) => {
            const { style, ...otherProps } = props;
            return (
              <StyledMenuItem
                {...otherProps}
                className={`custom-autocomplete-option ${selected ? 'selected' : ''}`}
              >
                {(option as any).label}
              </StyledMenuItem>
            );
          }}
          renderInput={(params) => (
            <StyledTextField
              {...params}
              isSmallScreen={isSmallScreen}
              error={!!error}
              helperText={error || ""}
              onBlur={onBlur}
              fullWidth
              label={
                <>
                  {field.label}
                  {field.required ? <span style={{ color: '#FF0000' }}> *</span> : <></>}
                </>
              }
              placeholder={field.placeholder}
              InputLabelProps={{
                shrink: true,
              }}
              sx={{
                '& .MuiInputBase-root': {
                  padding: 0,
                  ...(isReadOnly && {
                    backgroundColor: '#f5f5f5',
                    cursor: 'not-allowed',
                  }),
                },
                ...(isReadOnly
                  ? {
                    '& .MuiInputBase-input': {
                      cursor: 'not-allowed',
                      color: 'text.disabled',
                    },
                  }
                  : {
                    '& .MuiAutocomplete-popupIndicator': {
                      color: theme.palette.primary.main,
                    },
                  }),
              }}
            />
          )}
          getOptionLabel={(option) => {
            const opt = option as any;
            if (typeof opt === 'string') return opt;
            return opt.label || '';
          }}
          ListboxProps={{
            style: { maxHeight: '300px' },
          }}
          noOptionsText="Aucune option"
          clearIcon={<FontAwesome icon={faClose} width={18} sx={{ color: 'primary.main' }} />}
          forcePopupIcon={true}
          PaperComponent={(props) => (
            <Paper
              {...props}
              elevation={3}
              sx={{
                '& .MuiAutocomplete-listbox': {
                  '& .custom-autocomplete-option': {
                    '&.selected': {
                      backgroundColor: theme.palette.primary.main,
                      color: 'white',
                    },
                  },
                },
              }}
            />
          )}
        />
      );
    case 'file':
      return (
        <Box sx={{ display: 'flex', flexDirection: { sm: 'column', md: 'row' },justifyContent: 'space-between', alignItems: 'center' }}
        >
          <Typography
            sx={{
              color: isReadOnly ? "text.disabled" : "primary.main",
              fontSize: isSmallScreen ? pxToRem(13) : undefined,
            }}
          >
            {field.label}
            {isRequired ? <span style={{ color: '#FF0000' }}> *</span> : <></>}
          </Typography>

          <Button
            variant="contained"
            sx={{
              minHeight: '43px',
              textTransform: 'none',
              fontSize: isSmallScreen ? pxToRem(13) : undefined,
              ...(isReadOnly && {
                backgroundColor: 'action.disabledBackground',
                color: 'text.disabled',
              })
            }}
            endIcon={<FontAwesome icon={faFileArrowUp} width={18} />}
            disabled={isReadOnly}
            onClick={(e) => {
              const input = document.createElement('input');
              input.type = 'file';
              input.accept = field.accept || '*';
              input.onchange = (e) => {
                const file = (e.target as HTMLInputElement).files?.[0];
                onChange(field.name, file);
              };
              input.click();
            }}
          >
            <ConditionalComponent isValid={value} defaultComponent={'Importez un document'}>
            (value as File).name
            </ConditionalComponent>
          </Button>

          {error && (
            <FormHelperText error sx={{ mt: 0 }}>
              {error}
            </FormHelperText>
          )}
        </Box>
      );
    case 'address':
      return (
        <AddressMapSelector
          name={field.name}
          placeholder={field.placeholder}
          label={field.label || 'Adresse'}
          value={value || ''}
          onChange={(e) => onChange(field.name, e)}
          required={!!field.required}
          disabled={isReadOnly}
          error={error}
          isSmallScreen={isSmallScreen}
        />
      )
    default:
      return (
        <StyledTextField
          isSmallScreen={isSmallScreen}
          isReadOnly={isReadOnly}
          fullWidth
          error={!!error}
          helperText={error || ' '}
          onBlur={onBlur}
          required={isRequired}
          name={field.name}
          InputLabelProps={{
            shrink: true,
          }}
          sx={{
            '& .MuiFormHelperText-root': {
              visibility: error ? 'visible' : 'hidden',
              height: error ? 'auto' : '0px'
            }
          }}
          value={value || ''}
          onChange={(e) => onChange(field.name, e.target.value)}
          label={field.label}
          type={field.name === 'password' ? 'password' : 'text'}
          placeholder={field.placeholder}
          multiline={field.type === 'textarea'}
          InputProps={{
            readOnly: isReadOnly,
            endAdornment: field.icon ? (
              <InputAdornment position="end" >
                {typeof field.icon === 'string' ? (
                  <SvgColor
                    src={field.icon}
                    sx={{ width: isSmallScreen ? 16 : 20, height: isSmallScreen ? 16 : 20, color: isReadOnly ? 'text.disabled' : 'primary.main' }}
                  />
                ) : (
                  <FontAwesome
                    sx={{
                      cursor: field.name === 'contrat' ? 'pointer' : 'default',
                      ...(isReadOnly && { color: 'text.disabled' })
                    }}
                    onClick={(event) => openPopover && openPopover(event)}
                    icon={field.icon}
                    width={isSmallScreen ? 16 : 20}
                    color="primary.main"
                  />
                )}
              </InputAdornment>
            ) : <></>,
          }}
        />
      );
  }
}
