import React, { useEffect, useState } from 'react';
import { Grid } from '@mui/material';
import { driverFormFields } from '../utils/form-fields-driver';
import { TableType, type FormFieldType, type ModeType, type TableColumn } from '@/shared/types/common';
import type { IDriver, CircuiteInformations, IDriverType } from '@/shared/types/driver';
import ActionButtons from '@/shared/components/form/buttons-action';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import AvatarUploader from '@/shared/components/form/avatar-uploader';
import FormField from '@/shared/components/form/form-field';
import { AddressDTO } from '@/shared/types/client';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { useInfrastructureStore } from '@/shared/api/stores/admin-service/infrastructureStore';
import { useDriverForm } from '../hooks/use-driver-form';

interface DriverTabProps {
  renderField: (field: FormFieldType<IDriverType>, value?: string) => React.ReactNode;
  mode: ModeType;
  onSave: () => void;
  onClose: () => void;
  onEdit: () => void;
  driver: IDriverType;
  tableHead: TableColumn[];
  // Modification explicite de la prop
  onVehicleSelect: (vehicleId: string | number) => void;
}

export default function DriverTab({
  mode,
  onSave,
  onClose,
  onEdit,
  renderField,
  tableHead,
  driver,
  onVehicleSelect, // Destructuration explicite
}: DriverTabProps) {
  const { departmentNames, fetchDepartmentNames } = useInfrastructureStore();
  const { vehicleOptions } = useDriverForm(); // Assurez-vous d'avoir ce hook
  const [departmentOptions, setDepartmentOptions] = useState<{ label: string; value: string }[]>([]);
  const isReadOnly = mode === 'view';

  // Log pour vérifier les options de véhicules
  useEffect(() => {
    console.log('Vehicle Options in DriverTab:', vehicleOptions);
  }, [vehicleOptions]);

  useEffect(() => {
    fetchDepartmentNames();
  }, []);

  useEffect(() => {
    if (departmentNames.length > 0) {
      const options = departmentNames.map((department) => ({
        label: department.name,
        value: department.id.toString(),
      }));
      setDepartmentOptions(options);
    }
  }, [departmentNames]);

  useEffect(() => {
    console.log('INITIAL DRIVER DATA', driver);
    console.log('VEHICLE OPTIONS', vehicleOptions);
  }, [driver, vehicleOptions]);

  const formatAddress = (address: AddressDTO): string => {
    if (!address) return '';
    
    const parts = [
      address.street,
      address.zipCode,
      address.city,
      address.country
    ].filter(Boolean);
    
    return parts.join(', ');
  };

  const renderCustomField = (field: FormFieldType<IDriverType>) => {
    if (field.name === 'vehicle') {
      const selectedVehicle = driver.vehicle;
      
      const updatedField: FormFieldType<IDriverType> = {
        ...field,
        options: vehicleOptions.map(vehicle => ({
          value: vehicle.id.toString(),
          label: `${vehicle.vehiculeName} (${vehicle.immatriculation})`
        })),
        onChange: (name: string, value: string) => {
          console.log('VEHICLE CHANGE TRIGGERED', {
            name, 
            value, 
            currentDriver: driver
          });

          const vehicleId = Number(value);
          if (onVehicleSelect) {
            onVehicleSelect(vehicleId);
          }
        }
      };

      const initialVehicleValue = typeof selectedVehicle === 'string' 
        ? selectedVehicle 
        : selectedVehicle?.id?.toString();

      return renderField(updatedField, initialVehicleValue);
    }

    // NOUVEAU: Gestion spéciale pour le département
    if (field.name === 'departmentId') {
      const selectedDepartmentValue = 
        driver.departmentId?.toString() || 
        departmentOptions.find(opt => 
          opt.label.toLowerCase() === driver.departmentName?.toLowerCase()
        )?.value;

      const updatedField: FormFieldType<IDriverType> = {
        ...field,
        options: departmentOptions
      };

      return renderField(updatedField, selectedDepartmentValue);
    }

    // Gestion spéciale pour l'immatriculation
    if (field.name === 'immatriculation') {
      const viewField = {
        ...field,
        disabled: true,
        type: 'text'
      } as FormFieldType<IDriverType>;

      return renderField(viewField, driver.vehicle?.immatriculation);
    }

    // Autres champs restent inchangés
    return renderField(field);
  };

  return (
    <>
      <ConditionalComponent isValid={isReadOnly}>
        <EditExportButtons
          onEdit={onEdit}
          onExport={() => void 0}
          tooltipTitle={TableType.Driver}
          dataRow={driver}
          tableHead={tableHead}
        />
      </ConditionalComponent>
      <form onSubmit={(e) => {
        e.preventDefault(); // Prevent default form submission
        onSave(); // Trigger form save
      }}>
        <Grid container spacing={4}>
          <Grid item xs={12}>
            <AvatarUploader onUpload={() => void 0} isReadOnly={isReadOnly} />
          </Grid>
          {driverFormFields(departmentOptions, vehicleOptions).map((field) => (
            <Grid item xs={12} sm={4} key={field.name}>
              {renderCustomField(field)}
            </Grid>
          ))}
          {!isReadOnly ? (
            <Grid item xs={12}>
              <ActionButtons 
                onSave={onSave} 
                onCancel={onClose} 
                mode={mode} 
              />
            </Grid>
          ) : null}
        </Grid>
      </form>
    </>
  );
}
