import React, { useEffect, useState } from 'react';
import {
  Box,
  InputAdornment,
  IconButton,
  Popover,
  SelectChangeEvent,
  RadioGroup,
  Typography,
  Radio,
  Autocomplete,
  FormControlLabel,
  Paper,
  useTheme,
  FormHelperText,
  Button,
  Checkbox,
  Tooltip,
  TextFieldProps,
} 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, IPreparationCircuit, Circuit, ITripDriverAssignment, ITripDriverAssignmentDetails, TripCircuitDetails } from '@/shared/types/circuit';
import { ContractRequest } 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 { IAgent, IClient } from '@/shared/types/client';
import {
  IAttendanceSheet,
  IEtablissement,
  IResponsableEtablissement,
} from '@/shared/types/etablissement';
import { 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 { PassengerContact, Representative } from '@/shared/types/passenger';
import { Document } from '@/shared/types/document';
import { DepartmentRequest, Lot, LotRequest, SectorList, SectorRequest } from '@/shared/types/infrastructure';
import { IDemande } from '@/shared/types/demande';
import { IDocument, ISuiviDocument } from '@/shared/types/document';
import { ISupplierIntervention, ISupplierType, IVehicle } from '@/shared/types/flottes/vehicule';
import { IIntervention } from '@/shared/types/flottes/intervention';
import { IIncident } from '@/shared/types/flottes/incident';

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 { IForgotPasswordForm, 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 { EstablishmentManager, EstablishmentRequest, IHolidayImport } from '@/shared/types/establishment';
import { IRoadMapMileage } from '@/shared/types/driver-roadmap';
import { Interlocutor, IPassengerList } from '@/shared/types/passenger';
import dayjs from 'dayjs';
import { AttendanceSheet, IAttendanceNotCher, IAttendanceSheetCher } from '@/shared/types/attendance-sheet';
import { AmendmentPassengerDetails } from '@/shared/types/ammendment-passenger';
import { FormikAmendmentPassengerDetails } from '@/shared/sections/usager/components/usager-form/avenants-horaires/types/formik-types';
import { AmendmentCircuit } from '@/shared/types/ammendment-circuit';
import { AddDocumentRequestDTO, IDocumentRequest } from '@/shared/types/document-request';
import CustomTooltip from '../tooltips/tooltip-custom';
import { VehicleBrandModelRequest } from '@/shared/types/fleet-management/vehicle-brand-model';
import { VehicleRequest } from '@/shared/types/fleet-management/vehicle';
import { FuelSupplierRequestDTO } from '@/shared/types/fleet-management/fuelSupplier';
import { Intervention, ServiceProviderRequest } from '@/shared/types/fleet-management/service-provider';
import { VehicleRepairRequest } from '@/shared/types/fleet-management/vehicle-repair';
import { VehicleIncidentRequest } from '@/shared/types/fleet-management/vehicle-incident';
import { faPlus } from "@fortawesome/free-solid-svg-icons"

interface FormFieldProps {
  field:
  | FormFieldType<Circuit>
  | FormFieldType<ICircuit>
  | FormFieldType<ContractRequest>
  | FormFieldType<IChauffeur>
  | FormFieldType<ITripDriverAssignment>
  | FormFieldType<ITrajet>
  | FormFieldType<TripCircuitDetails>
  | FormFieldType<IPassengerList>
  | FormFieldType<IAvenant>
  | FormFieldType<FormikAmendmentPassengerDetails>
  | FormFieldType<AmendmentPassengerDetails>
  | FormFieldType<IAbsence>
  | FormFieldType<IClient>
  | FormFieldType<IEtablissement>
  | FormFieldType<IResponsableEtablissement>
  | FormFieldType<EstablishmentRequest>
  | FormFieldType<EstablishmentManager>
  | FormFieldType<IVacance>
  | FormFieldType<IAttendanceSheet>
  | FormFieldType<IDriverType>
  | FormFieldType<Interlocutor>
  | 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<IFormulaire>
  | FormFieldType<IDocument>
  | FormFieldType<ISuiviDocument>
  | FormFieldType<IDemande>
  | FormFieldType<IRHAbsence>
  | FormFieldType<CalendarEvent>
  | FormFieldType<AgencyRequest>
  | FormFieldType<DepartmentRequest>
  | FormFieldType<Lot>
  | FormFieldType<LotRequest>
  | FormFieldType<SectorList>
  | FormFieldType<SectorRequest>
  | FormFieldType<IHolidayImport>
  | FormFieldType<VehicleRequest>
  | FormFieldType<VehicleIncidentRequest>
  | FormFieldType<IIntervention>
  | FormFieldType<IMileage>
  | FormFieldType<Document>
  | FormFieldType<IAgent>
  | FormFieldType<IRole>
  | FormFieldType<IEquipe>
  | FormFieldType<ModuleFormData>
  | FormFieldType<InterventionFormData>
  | FormFieldType<IVehicleAffectation>
  | FormFieldType<IFuelFee>
  | FormFieldType<IFuelHistory>
  | FormFieldType<VehicleBrandModelRequest>
  | FormFieldType<ITankerType>
  | FormFieldType<IFuelImport>
  | FormFieldType<IPassword>
  | FormFieldType<INotification>
  | FormFieldType<IRoadMapMileage>
  | FormFieldType<TeamRequest>
  | FormFieldType<ILanguageSettings>
  | FormFieldType<Representative>
  | FormFieldType<PassengerContact>
  | FormFieldType<IAttendanceNotCher>
  | FormFieldType<IAttendanceSheetCher>
  | FormFieldType<AttendanceSheet>
  | FormFieldType<IForgotPasswordForm>
  | FormFieldType<AmendmentCircuit>
  | FormFieldType<IDocumentRequest>
  | FormFieldType<AddDocumentRequestDTO>
  | FormFieldType<ServiceProviderRequest>
  | FormFieldType<ISupplierIntervention>
  | FormFieldType<Intervention>
  | FormFieldType<ITripDriverAssignmentDetails>
  | FormFieldType<FuelSupplierRequestDTO>
  | FormFieldType<VehicleRepairRequest>;

  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;
  onAddInfrastructure?: () => void;
  onAddContract?: () => void;
  onAddEstablishment?: () => void;
  onAddClient?: () => 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,
  disabled = false,
  isDrawerElement,
  formData,
  error,
  onBlur,
  onAddInfrastructure,
  onAddContract,
  onAddEstablishment,
  onAddClient
}: 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 if (field.type === 'multiple') {
      // Pour les champs multiples, event.target.value est déjà un tableau
      const selectedValues = event.target.value as string[];

      // Conversion spéciale pour lotsId qui attend des nombres
      if (field.name === 'lotsId') {
        const numericValues = selectedValues.map(val => Number(val));
        onChange(field.name, numericValues);
      } else {
        onChange(field.name, selectedValues);
      }
    } 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 || ''}`;
    }
    // Normalisation: convertir les nombres en chaînes pour les selects simples
    if (field.type !== 'multiple' && typeof value === 'number') {
      return String(value);
    }
    if (field.type === 'multiple') {
      if (Array.isArray(value)) {
        if (value.length > 0 && typeof value[0] === 'object' && value[0] !== null && 'id' in value[0]) {
          return value.map((v) => String(v.id));
        }
        // Conversion spéciale pour lotsId qui contient des nombres
        if (field.name === 'lotsId') {
          return value.map((v) => String(v));
        }
        return value.map((v) => String(v));
      }
      return [];
    }
    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) => {
              if (dayjs(newDate).isValid() && dayjs(newDate).year() >= 1800) {
                const dateString = dayjs(newDate).startOf('day').format('YYYY-MM-DDTHH:mm:ss');
                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) => {
                  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} sx={{ position: 'relative' }}>
          <StyledInputLabel id={field.name}>
            {field.label}
            {isRequired ? <span style={{ color: '#FF0000' }}> *</span> : null}
          </StyledInputLabel>

          <StyledSelect
            sx={{
              fontSize: isSmallScreen ? pxToRem(13) : undefined,
            }}
            name={field.name}
            required={isRequired}
            labelId={field.name}
            value={getSelectValue()}
            onBlur={onBlur}
            onChange={handleSelectChange}
            disabled={isReadOnly || disabled}
            MenuProps={{
              PaperProps: { style: { maxHeight: 300 } },
            }}
            readOnly={isReadOnly}
            multiple={field.type === 'multiple'}
            displayEmpty
            IconComponent={(field.hasAddInfrastructureModal || field.hasAddClientModal) ? () => null : undefined}
            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>
                );
              }

              if (field.type === 'multiple') {
                if (field.name === 'usagers' && (selected as string[]).length > 1) {
                  return (selected as string[]).length.toString();
                }

                return (selected as string[]).map(val => {
                  const option = field.options?.find(opt => opt.value === val);
                  return option ? option.label : val;
                }).join(', ');
              }
              return field.options?.find((option) => option.value === selected)?.label || '';
            }}



          >
            {field.options?.map((option) => (
              <StyledMenuItem
                key={option.value}
                value={option.value}
                sx={{
                  ...(field.name === 'driverId' && {
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'flex-start',
                    py: 0.5,
                    px: 1,
                    '&:hover': {
                      backgroundColor: 'primary.lighter',
                    },
                  })
                }}
              >
                <ConditionalComponent
                  isValid={field.name === 'driverId' && (option as any).rank}
                  defaultComponent={option.label}
                >
                  <Box sx={{ width: '100%' }}>
                    <Typography variant="body2" sx={{ fontWeight: 'bold', color: 'text.primary', mb: 0.5 }}>
                      {(option as any).label.split(' - ')[0]}
                    </Typography>
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 0.5 }}>
                      <ConditionalComponent
                        isValid={(option as any).emptyDistanceKm !== undefined}
                        defaultComponent={null}
                      >
                        <CustomTooltip title="Distance à vide (proximité)" arrow>
                          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                            <Typography variant="caption" sx={{ color: 'primary.main', fontWeight: 'medium' }}>
                              🚗
                            </Typography>
                            <Typography variant="caption" sx={{ color: 'primary.main', fontWeight: 'medium' }}>
                              {(option as any).emptyDistanceKm?.toFixed(2) || '0.00'} km
                            </Typography>
                          </Box>
                        </CustomTooltip>
                      </ConditionalComponent>
                      <ConditionalComponent
                        isValid={(option as any).rank !== undefined}
                        defaultComponent={null}
                      >
                        <CustomTooltip title="Classement du chauffeur" arrow>
                          <Box sx={{
                            display: 'flex',
                            alignItems: 'center',
                            gap: 0.5,
                            backgroundColor: 'primary.lighter',
                            borderRadius: '8px',
                            px: 1,
                            py: 0.3
                          }}>
                            <Typography variant="caption" sx={{
                              color: 'primary.main',
                              fontWeight: 'bold',
                              fontSize: '0.75rem'
                            }}>
                              #{(option as any).rank}
                            </Typography>
                          </Box>
                        </CustomTooltip>
                      </ConditionalComponent>
                    </Box>
                  </Box>
                </ConditionalComponent>
              </StyledMenuItem>
            ))}
          </StyledSelect>

          <ConditionalComponent isValid={!!field.hasAddInfrastructureModal}>
            <CustomTooltip title="Créer une nouvelle infrastructure" arrow>
              <IconButton
                color="primary"
                size="small"
                onClick={() => { onAddInfrastructure?.() }}
                sx={{
                  position: 'absolute',
                  top: '50%',
                  right: 12,
                  transform: 'translateY(-50%)',
                  padding: 0,
                  zIndex: 2,
                  '&:hover': { backgroundColor: 'transparent', color: 'primary.dark' },
                }}
              >
                <FontAwesome icon={faPlus} />
              </IconButton>
            </CustomTooltip>
          </ConditionalComponent>

          <ConditionalComponent isValid={!!field.hasAddClientModal}>
            <CustomTooltip title="Créer un nouveau client" arrow>
              <IconButton
                color="primary"
                size="small"
                onClick={() => onAddClient?.()}
                sx={{
                  position: 'absolute',
                  top: '50%',
                  right: 12,
                  transform: 'translateY(-50%)',
                  padding: 0,
                  zIndex: 2,
                  '&:hover': { backgroundColor: 'transparent', color: 'primary.dark' },
                }}
              >
                <FontAwesome icon={faPlus} />
              </IconButton>
            </CustomTooltip>
          </ConditionalComponent>


          {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={isReadOnly && !(formData && (formData as any).mode === 'add' || (formData as any).mode === 'copy')}
                  aria-label={showPassword ? 'Masquer le mot de passe' : 'Afficher le mot de passe'}
                >
                  <FontAwesome icon={showPassword ? faEyeSlash : faEye} />
                </IconButton>
              </InputAdornment>
            ) : (
              <></>
            ),
          }}
          onCopy={(e: any) => { if (field.name === 'password') e.preventDefault(); }}
          onCut={(e: any) => { if (field.name === 'password') e.preventDefault(); }}
          onPaste={(e: any) => { if (field.name === 'password') e.preventDefault(); }}
        />
      );
    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.length > 0
              ? options.find((opt) => opt.value === value.toString()) || {
                label: value.toString(),
                value: value.toString(),
              }
              : null
          }
          onInputChange={(event, newInputValue) => {
            if (field.onSearch) {
              field.onSearch(newInputValue);
            }
          }}
          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, '');
            }
          }}
          filterOptions={field.onSearch ? (x) => x : undefined}
          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> : null}
                </>
              }
              placeholder={field.placeholder}
              InputLabelProps={{ shrink: true }}
              InputProps={{
                ...params.InputProps,
                endAdornment: (
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                    <ConditionalComponent isValid={!!field.hasAddInfrastructureModal}>
                      <CustomTooltip title="Créer une nouvelle infrastructure" arrow>
                        <IconButton
                          color="primary"
                          onClick={() => onAddInfrastructure?.()}
                          edge="end"
                          size="small"
                        >
                          <FontAwesome icon={faPlus} />
                        </IconButton>
                      </CustomTooltip>
                    </ConditionalComponent>

                    <ConditionalComponent isValid={!!field.hasAddContractModal}>
                      <CustomTooltip title="Créer un nouveau contrat" arrow>
                        <IconButton
                          color="primary"
                          onClick={() => onAddContract?.()}
                          edge="end"
                          size="small"
                        >
                          <FontAwesome icon={faPlus} />
                        </IconButton>
                      </CustomTooltip>
                    </ConditionalComponent>

                    <ConditionalComponent isValid={!!field.hasAddEstablishmentModal}>
                      <CustomTooltip title="Créer un nouvel établissement" arrow>

                        <IconButton
                          color="primary"
                          onClick={() => onAddEstablishment?.()}
                          edge="end"
                          size="small"
                        >
                          <FontAwesome icon={faPlus} />
                        </IconButton>
                      </CustomTooltip>
                    </ConditionalComponent>

                    {params.InputProps.endAdornment}
                  </Box>


                ),
              }}


              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 'combobox-multiple':
      const optionsMultiple = field.options || [];
      return (
        <Autocomplete
          multiple
          options={optionsMultiple}
          value={
            value && optionsMultiple.length > 0
              ? optionsMultiple.filter((opt) => value.includes(opt.value.toString()))
              : []
          }
          onInputChange={(event, newInputValue) => {
            if (field.onSearch) {
              field.onSearch(newInputValue);
            }
          }}
          disabled={isReadOnly}
          onChange={(event, newValue) => {
            if (Array.isArray(newValue)) {
              const selectedValues = newValue.map((item: any) => item.value);
              onChange(field.name, selectedValues);
            } else {
              onChange(field.name, []);
            }
          }}
          filterOptions={field.onSearch ? (x) => x : undefined}
          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
          disabled={disabled}
          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 || disabled) ? 'text.disabled' : 'primary.main' }}
                  />
                ) : (
                  <FontAwesome
                    sx={{
                      cursor: field.name === 'contrat' ? 'pointer' : 'default',
                      ...((isReadOnly || disabled) && { color: 'text.disabled' })
                    }}
                    onClick={(event) => openPopover && openPopover(event)}
                    icon={field.icon}
                    width={isSmallScreen ? 16 : 20}
                    color="primary.main"
                  />
                )}
              </InputAdornment>
            ) : <></>,
          }}
        />
      );
  }
}
