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';

interface DriverTabProps {
  renderField: (field: FormFieldType<IDriverType>, value?: string) => React.ReactNode;
  mode: ModeType;
  onSave: () => void;
  onClose: () => void;
  onEdit: () => void;
  driver: IDriverType;
  tableHead: TableColumn[];
}

export default function DriverTab({
  mode,
  onSave,
  onClose,
  onEdit,
  renderField,
  tableHead,
  driver
}: DriverTabProps) {
  const { departmentNames, fetchDepartmentNames } = useInfrastructureStore();
  const [departmentOptions, setDepartmentOptions] = useState<{ label: string; value: string }[]>([]);
  const isReadOnly = mode === 'view';

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

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

  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 === 'departmentId') {
      console.log('Department Rendering Debug:', {
        driver,
        departmentOptions,
        currentValue: driver.departmentId,
        currentName: driver.departmentName
      });

      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);
    }

    if (isReadOnly && field.name === 'circuitNames') {
      const viewField = {
        ...field,
        label: 'Circuits',
        type: 'text',
        readOnly: true
      };
      
      const circuitInfos = driver.circuitNames as unknown as CircuiteInformations[];
      let displayValue = '';
      
      if (Array.isArray(circuitInfos) && circuitInfos.length > 0) {
        displayValue = circuitInfos
          .filter(circuit => circuit != null)
          .map(circuit => {
            if (circuit) {
              return circuit.titled || circuit.circuitCode || 'Circuit sans nom';
            }
            return 'Circuit sans nom';
          })
          .join(', ');
      }
      
      return (
        <FormField
          field={viewField as FormFieldType<any>}
          value={displayValue || 'Aucun circuit'}
          onChange={() => {}}
          isReadOnly={true}
        />
      );
    }

    if (isReadOnly && field.name === 'addresses' && driver.addresses && driver.addresses.length > 0) {
      const viewField = {
        ...field,
        type: 'text',
        readOnly: true
      };
      
      const addressString = formatAddress(driver.addresses[0]);
      
      return (
        <FormField
          field={viewField as FormFieldType<any>}
          value={addressString}
          onChange={() => {}}
          isReadOnly={true}
        />
      );
    }

    if (isReadOnly && field.name === 'drivingLicenseName') {
      const permisLabel = field.options?.find(opt => opt.value === driver.drivingLicenseName)?.label || 'Non spécifié';
      
      const viewField = {
        ...field,
        type: 'text',
        readOnly: true
      };
      
      return (
        <FormField
          field={viewField as FormFieldType<any>}
          value={permisLabel}
          onChange={() => {}}
          isReadOnly={true}
        />
      );
    }

    if (isReadOnly && field.name === 'fuelCardNames') {
      const viewField = {
        ...field,
        type: 'text',
        readOnly: true
      };
      
      const cardsDisplay = Array.isArray(driver.fuelCardNames) && driver.fuelCardNames.length > 0 
        ? driver.fuelCardNames.join(', ') 
        : 'Aucune carte carburant';
      
      return (
        <FormField
          field={viewField as FormFieldType<any>}
          value={cardsDisplay}
          onChange={() => {}}
          isReadOnly={true}
        />
      );
    }

    if (isReadOnly && field.name === 'driverStatus') {
      const statusLabel = field.options?.find(opt => opt.value === driver.driverStatus)?.label || driver.driverStatus;
      
      const viewField = {
        ...field,
        type: 'text',
        readOnly: true
      };
      
      return (
        <FormField
          field={viewField as FormFieldType<any>}
          value={statusLabel}
          onChange={() => {}}
          isReadOnly={true}
        />
      );
    }

    if (isReadOnly && field.name === 'mapAdresse' && driver.addresses && driver.addresses.length > 0) {
      const addressString = driver.addresses[0].street + 
        (driver.addresses[0].additionalAddress ? `, ${driver.addresses[0].additionalAddress}` : '') +
        `, ${driver.addresses[0].zipCode} ${driver.addresses[0].city}`;
      
      const viewField = {
        ...field,
        type: 'text',
        readOnly: true
      };
      
      return (
        <FormField
          field={viewField as FormFieldType<any>}
          value={addressString}
          onChange={() => {}}
          isReadOnly={true}
        />
      );
    }

    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).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>
    </>
  );
} 