'use client';

import { useEffect, useState, useMemo } from 'react';
import { Grid, Typography } from '@mui/material';
import { useFormik } from 'formik';
import { useInfrastructureStore } from '@/shared/api/stores/admin-service/infrastructureStore';
import { useDriverForm } from '../hooks/use-driver-form';

import FormField from '@/shared/components/form/form-field';
import {  type FormFieldType, type ModeType, type TableColumn } from '@/shared/types/common'; 
import FormContainer from '@/layouts/form/form-container';
import { IDriverType } from '@/shared/types/driver';
import { AddButton } from '@/shared/components/table/styles';
import FontAwesome from '@/shared/components/fontawesome';
import { faFileArrowUp } from '@fortawesome/free-solid-svg-icons';
import { driverSchema } from '../utils/driver-validation';
import TabbedForm from '@/shared/components/tabs/tabbed-form';
import DocumentForm from '@/shared/components/documents/documents-form';
import DriverTab from '../components/driver-tab';
import DriverTripsTable from '../components/driver-trips-table';

interface DriverFormProps {
  driver: IDriverType;
  mode: ModeType;
  onSave: (updatedDriver: IDriverType) => void;
  onEdit: (updatedDriver: IDriverType) => void;
  onClose: (saved?: boolean) => void;
  tableHead: TableColumn[];
  setHasUnsavedChanges: (hasUnsavedChanges: boolean) => void;
  updateTabContent: (tabId: string, content: IDriverType) => void;
  tabId: string;
}



export default function DriverForm({
  driver,
  mode,
  onSave,
  onClose,
  onEdit,
  tableHead,
  setHasUnsavedChanges,
  updateTabContent,
  tabId,
}: DriverFormProps) {
  const [departmentOptions, setDepartmentOptions] = useState<{ label: string; value: string }[]>([]);
  const { departmentNames, fetchDepartmentNames } = useInfrastructureStore();
  const { getDepartmentHexColorById } = useInfrastructureStore();
  const { vehicleOptions } = useDriverForm();

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

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

 

  const processedDriver = useMemo(() => {
    const baseDriver = { ...driver };

    if (driver.departmentId || driver.departmentName) {
      const matchingDepartment = departmentNames.find(
        dept => 
          dept.id === driver.departmentId || 
          dept.name === driver.departmentName
      );

      if (matchingDepartment) {
        baseDriver.departmentId = matchingDepartment.id;
        baseDriver.departmentName = matchingDepartment.name;
      }
    }

    if (driver.addresses && driver.addresses.length > 0) {
      const address = driver.addresses[0];
      baseDriver.mapAdresse = {
        address: address.street,
        city: address.city,
        country: address.country,
        postalCode: address.zipCode,
        lat: address.latitude,
        lng: address.longitude,
        formattedAddress: `${address.street}, ${address.zipCode} ${address.city}, ${address.country}`
      };
    }

    if (driver.vehicle && typeof driver.vehicle === 'object') {
      baseDriver.immatriculation = driver.vehicle.immatriculation;
      baseDriver.fuelCardNames = driver.vehicle.fuelCardNumber ? [driver.vehicle.fuelCardNumber] : [];
      baseDriver.fuelVolume = driver.vehicle.fuelCardType;
    } else if (driver.vehicle && vehicleOptions.length > 0) {
      const vehicleId = typeof driver.vehicle === 'string' ? Number(driver.vehicle) : driver.vehicle;
      const matchingVehicle = vehicleOptions.find(v => v.id === vehicleId);
      
      if (matchingVehicle) {
        baseDriver.vehicle = matchingVehicle;
        baseDriver.immatriculation = matchingVehicle.immatriculation;
        baseDriver.fuelCardNames = [matchingVehicle.fuelCardNumber];
        baseDriver.fuelVolume = matchingVehicle.fuelCardType;
      }
    }

    return baseDriver;
  }, [driver, departmentNames, vehicleOptions]);

  const formik = useFormik<IDriverType>({
    initialValues: {
      ...processedDriver,
      fuelCardNames: processedDriver.fuelCardNames || [],
      fuelVolume: processedDriver.fuelVolume || '',
      immatriculation: processedDriver.immatriculation || '',
    },
    validationSchema: driverSchema,
    onSubmit: async (values) => {
      try {
        await onSave(values);
        if (setHasUnsavedChanges) setHasUnsavedChanges(false);
        onClose(true);
      } catch (error) {
        console.error('Error saving driver:', error);
      }
    },
    enableReinitialize: true, 
  });
  useEffect(() => {
    const fetchColor = async () => {
      const departmentId = formik.values.departmentId;
      if (departmentId) {
        try {
          const color = await getDepartmentHexColorById(departmentId.toString());
          formik.setFieldValue('colorCode', color);
        } catch (error) {
          console.error('Failed to fetch department color:', error);
        }
      }
    };
  
    fetchColor();
  }, [formik.values.departmentId]);
  
  useEffect(() => {
    if (updateTabContent && tabId && (mode !== "view")) {
      const timer = setTimeout(() => {
        updateTabContent(tabId, formik.values)
      }, 300)
      return () => {
        clearTimeout(timer)
      }
    }
  }, [formik.values, updateTabContent, tabId, mode])

  useEffect(() => {
    console.log('Department Options Updated:', {
      departmentNames,
      processedDriver: processedDriver
    });
  }, [departmentNames, processedDriver]);

  useEffect(() => {
    // Initialisation automatique du véhicule lors du chargement
    if (processedDriver.vehicle && vehicleOptions.length > 0) {
      console.log('INITIAL VEHICLE DATA', processedDriver.vehicle);
      
      // Les valeurs sont déjà traitées dans processedDriver
      if (typeof processedDriver.vehicle === 'object') {
        // Pas besoin de traitement supplémentaire, les valeurs sont déjà dans processedDriver
        console.log('Vehicle data already processed');
      }
    }
  }, [processedDriver, vehicleOptions]);

  const renderField = (
    field: FormFieldType<IDriverType>, 
    initialValue?: string | number
  ) => {
    const isColorCodeAutoFilled = field.name === 'colorCode';
    return (
      <FormField
        field={field}
        value={initialValue ?? formik.values[field.name as keyof IDriverType]}
        error={
          formik.touched[field.name as keyof IDriverType]
            ? (formik.errors[field.name as keyof IDriverType] as string)
            : undefined
        }
        onChange={(name, value) => formik.setFieldValue(name, value)}
        onBlur={formik.handleBlur}
        isReadOnly={mode === 'view' || isColorCodeAutoFilled}
        />
    );
  };

  const handleVehicleSelect = (vehicleId: number | string) => {
    const vehicleIdNumber = Number(vehicleId);

    const selectedVehicle = vehicleOptions.find(
      v => v.id === vehicleIdNumber || v.id.toString() === vehicleId.toString()
    );

    if (selectedVehicle) {
      formik.setFieldValue('vehicle', selectedVehicle);
      
      // Assurez-vous que fuelCardNames est un tableau
      const fuelCardNames = selectedVehicle.fuelCardNumber 
        ? [selectedVehicle.fuelCardNumber] 
        : [];
      
      formik.setFieldValue('immatriculation', selectedVehicle.immatriculation);
      formik.setFieldValue('fuelCardNames', fuelCardNames);
      formik.setFieldValue('fuelVolume', selectedVehicle.fuelCardType);
    }
  };

  const tabs = [
    {
      label: 'Chauffeur',
      content: (
        <DriverTab
          renderField={renderField}
          driver={driver}
          mode={mode}
          onSave={() => {
            formik.validateForm().then(() => {
              formik.submitForm();
            });
          }}
          onClose={onClose}
          onEdit={() => onEdit(formik.values)}
          tableHead={tableHead}
          onVehicleSelect={handleVehicleSelect}
        />
      ),
    },
    {
      label: 'Trajets Assignés',
      content: (
        <DriverTripsTable
          driverId={
            driver.id && 
            driver.id !== '' && 
            !isNaN(Number(driver.id)) 
              ? Number(driver.id) 
              : undefined
          }
        />
      ),
    },
    {
      label: 'Documents',
      content: <DocumentForm documents={[]} />,
    },
    {
      label: 'Véhicule',
      content: (
        <div>
          <Typography variant="subtitle1">Informations sur le véhicule</Typography>
          <Grid container spacing={4}>
            <Grid
              item
              xs={12}
              sm={4}
              sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}
            >
              <Typography
                sx={{
                  color: mode === 'view' ? 'text.disabled' : 'primary.main',
                  display: { sm: 'none', md: 'block' },
                }}
              >
                Importer document
              </Typography>
              <AddButton
                variant="contained"
                sx={{ minHeight: '43px' }}
                endIcon={<FontAwesome icon={faFileArrowUp} width={18} />}
                disabled={mode === 'view'}
              >
                Importez un document
              </AddButton>
            </Grid>
          </Grid>
        </div>
      ),
    },
  ];

  return (
    <FormContainer titre="Fiche Chauffeur">
      <TabbedForm tabs={tabs} />
    </FormContainer>
  );
}

