'use client';

import React, { useEffect, useState, useMemo } from 'react';
import { Grid } from '@mui/material';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { fr } from 'date-fns/locale';
import { IAppointment } from '@/shared/types/appointment';
import { formFields } from '../utils/form-fields-appointment';
import FormField from '@/shared/components/form/form-field';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import ActionButtons from '@/shared/components/form/buttons-action';
import FormContainer from '@/layouts/form/form-container';
import { useFormik } from 'formik';
import { appointmentSchema } from '../utils/appiontement-schema';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { useDriverStore } from '@/shared/api/stores/driverStore';
import { IActiveDriver } from '@/shared/types/driver';

interface AppointmentFormProps {
  appointment: IAppointment;
  mode?: 'add' | 'edit' | 'view' | 'copy';
  onSave: (updatedAppointment: IAppointment) => Promise<boolean>;
  onEdit: (appointment: IAppointment) => void;
  onClose: (forceClose: boolean) => void;
  updateTabContent: (tabId: string, newContent: IAppointment) => void;
  tabId: string;
}

export default function AppointmentForm({
  appointment,
  mode = 'add',
  onSave,
  onClose,
  onEdit,
  updateTabContent,
  tabId,
}: AppointmentFormProps) {
  const isReadOnly = mode === 'view';
  const { getActiveDrivers} = useDriverStore();
  const [activeDrivers, setActiveDrivers] = useState<IActiveDriver[]>([]);
  const [driversLoading, setDriversLoading] = useState(false);

  useEffect(() => {
    const loadActiveDrivers = async () => {
      setDriversLoading(true);
      try {
        const drivers = await getActiveDrivers();
        setActiveDrivers(drivers);
      } catch (error) {
      } finally {
        setDriversLoading(false);
      }
    };

    loadActiveDrivers();
  }, [getActiveDrivers]);

  const driverOptions = useMemo(() => {
    if (driversLoading) {
      return [{ value: '', label: 'Chargement des chauffeurs...' }];
    }
    
    if (activeDrivers.length === 0) {
      return [{ value: '', label: 'Aucun chauffeur disponible' }];
    }
    
    return activeDrivers.map(driver => ({
      value: driver.id.toString(), 
      label: driver.name,           
    }));
  }, [activeDrivers, driversLoading]);

  const dynamicFormFields = useMemo(() => {
    return formFields.map(field => {
      if (field.name === 'driverName') {
        return {
          ...field,
          options: driverOptions,
        };
      }
      return field;
    });
  }, [driverOptions]);

  const getFieldValue = (fieldName: string) => {
    if (fieldName === 'driverName') {
      const driverName = formik.values.driverName;
      if (driverName && activeDrivers.length > 0) {
        const driver = activeDrivers.find(d => d.name === driverName);
        return driver ? driver.id.toString() : formik.values.driverId || '';
      }
      return formik.values.driverId || '';
    }
    return formik.values[fieldName as keyof IAppointment];
  };

  const formik = useFormik<IAppointment>({
    initialValues: appointment,
    validationSchema: appointmentSchema,
    onSubmit: async (values) => {
      try {
        const success = await onSave(values);
        if (success) {
          onClose(true);
        }
      } catch (error) {
        console.error('Erreur lors de la sauvegarde:', error);
      }
    },
    enableReinitialize: true
  });

  useEffect(() => {
    if (updateTabContent && tabId && mode !== "view") {
        updateTabContent(tabId, formik.values)
    }
  }, [formik.values, updateTabContent, tabId, mode])

  const handleChange = (name: string, value: any) => {
    if (name === 'driverName' && (value === '' || value.includes('Chargement') || value.includes('Aucun chauffeur'))) {
      return;
    }

    if (name === 'driverName') {
      const selectedDriver = activeDrivers.find(driver => driver.id.toString() === value);
      if (selectedDriver) {
        formik.setFieldValue('driverId', selectedDriver.id.toString());
        formik.setFieldValue('driverName', selectedDriver.name);
        return;
      }
    }

    if (name === 'type' && value !== 'Visite Médicale (médecine du travail)') {
      formik.setFieldValue('medicalCenterId', '');
      formik.setFieldValue('doctorId', '');
      formik.setFieldValue('medicalCenterName', '');
      formik.setFieldValue('doctorName', '');
    }

    if (name === 'type' && value !== 'Autre') {
      formik.setFieldValue('otherType', '');
    }
    
    formik.setFieldValue(name, value);
  };

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={fr}>
      <FormContainer titre="Rendez-vous">
        <ConditionalComponent isValid={isReadOnly}>
          <EditExportButtons
            onEdit={() => onEdit(appointment)}
            onExport={() => void 0}
            tooltipTitle="le rendez-vous"
          />
        </ConditionalComponent>
  
        <form onSubmit={formik.handleSubmit}>
          <Grid container spacing={3}>
            {dynamicFormFields.map((field) => (
              <Grid item xs={12} md={4} key={field.name}>
                <FormField
                  field={field}
                  value={getFieldValue(field.name)}
                  onChange={handleChange}
                  error={
                    formik.touched[field.name]
                      ? (formik.errors[field.name] as string | undefined)
                      : undefined
                  }
                  onBlur={formik.handleBlur}
                  isReadOnly={Boolean(isReadOnly || (field.isDisabled && field.isDisabled(formik.values)) || (field.name === 'driverName' && driversLoading))}
                />
              </Grid>
            ))}
            <Grid item xs={12}>
                <ActionButtons 
                  onSave={() => formik.handleSubmit()} 
                  onCancel={() => onClose(false)} 
                  mode={mode}
                />
            </Grid>
          </Grid>
        </form>
      </FormContainer>
    </LocalizationProvider>
  );
}
