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

interface DriverFormProps {
  driver: IDriverType;
  mode: ModeType;
  onSave: (updatedDriver: IDriverType) => void;
  onEdit: (updatedDriver: IDriverType) => void;
  onClose: () => 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();

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

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

  const formik = useFormik<IDriverType>({
    initialValues: processedDriver,
    validationSchema: driverSchema,
    onSubmit: async (values) => {
      try {
        await onSave(values);
        if (setHasUnsavedChanges) setHasUnsavedChanges(false);
        onClose();
      } catch (error) {
        console.error('Error saving driver:', error);
      }
    },
    enableReinitialize: true, 
  });
  
  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]);

  const renderField = (
    field: FormFieldType<IDriverType>, 
    initialValue?: string | number
  ) => {
    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'}
      />
    );
  };

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

