'use client';

import { Grid} from '@mui/material';
import { useEffect } from 'react';
import CircuitTabForm from '../components/circuit-form/circuit-form';
import CircuittrajetsForm from '../components/circuit-form/trajet/trajets-list';
import { Circuit } from '@/shared/types/circuit';
import AvenantList from '../components/circuit-form/avenant/avenants-list';
import FormField from '@/shared/components/form/form-field';
import { FormFieldType, ModeType } from '@/shared/types/common';
import ChauffeurList from '../components/circuit-form/chauffeur/chauffeur-list';
import TabbedForm from '@/shared/components/tabs/tabbed-form';
import FormContainer from '@/layouts/form/form-container';
import CircuitUsager from '../components/circuit-form/usager/circuit-usager';
import { _documents } from '@/shared/_mock/_documents';
import { FormikProvider, useFormik } from 'formik';
import { circuitSchema } from '../utils/circuit-validation';
import { formConfig } from '../utils/form-fields-circuit';
import { useCircuitStore } from '@/shared/api/stores/circuit-service/circuitStore';
import { enqueueSnackbar } from 'notistack';
import CircuitDepotDocumentForm from '../components/circuit-form/document/circuit-depot-document';

interface CircuitFormProps {
  circuit: Circuit;
  mode: ModeType;
  onEdit: (updatedContract: Circuit) => void;
  onClose: (isSaved: boolean) => void;
  updateTabContent: (tabId: string, content: Circuit) => void;
  tabId: string;
  markTabAsSaved: (tabId: string, content: Circuit) => void;    
  hasUnsavedChanges?: boolean;
  setTabReplaceCurrentTab: (tabId: string, replaceCurrentTab: boolean) => void;
}
export interface RenderFieldOptions {
  onAddContract?: () => void;
  onAddMainEstablishment?:()=> void ;
}

export default function CircuitForm({ circuit, mode, onClose, onEdit, updateTabContent, tabId, markTabAsSaved, hasUnsavedChanges, setTabReplaceCurrentTab }: CircuitFormProps) {
 
  const isReadOnly = mode === 'view';
  const isAddMode = mode === 'add';
  const isEditMode = mode === 'edit';
  
  const { addCircuit, loading, updateCircuit } = useCircuitStore();
  
  const formik = useFormik<Circuit>({
    initialValues: circuit,
    validationSchema: circuitSchema,
    onSubmit: (values) => {
      handleFormSubmit(values);
    },
    enableReinitialize: true
  });

  useEffect(() => {
    if (updateTabContent && tabId && mode !== "view") {
      const timer = setTimeout(() => {
        updateTabContent(tabId, formik.values)
      }, 300)

      return () => {
        clearTimeout(timer)
      }
    }
  }, [formik.values, updateTabContent, tabId, mode])


  const handleFormSubmit = async (values: Circuit) => {
    try {
      if (isEditMode) {
        await updateCircuit(values);
        enqueueSnackbar("Circuit modifié avec succès", { variant: 'success' });
        markTabAsSaved(tabId, values)
        formik.resetForm({ values })
        } else if (mode === 'add' || mode === 'copy') {
        const { id, createdAt, updatedAt, lotIds, ...valuesWithoutId } = values;
        const addedCircuit = await addCircuit({...valuesWithoutId, lotIds: lotIds || [] });
        markTabAsSaved(tabId, addedCircuit)
        formik.resetForm({ values: addedCircuit as Circuit });
        enqueueSnackbar("Circuit ajouté avec succès", { variant: 'success' });
        setTabReplaceCurrentTab(tabId, true);
      }
    } catch (error: any) {
      enqueueSnackbar(error.message, { variant: 'error' });
    }
  };

  useEffect(() => {
    if (formik.dirty && !hasUnsavedChanges) {
      formik.resetForm();
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [hasUnsavedChanges])

  const renderField = (field: FormFieldType<Circuit>,options?: RenderFieldOptions) => {
    const error = formik.touched[field.name] && formik.errors[field.name];
    const shouldConvertToString = [
      'mainDriver', 
      'mainEstablishment', 
      'timeTolerance'
    ].includes(field.name);
    const fieldValue = shouldConvertToString 
      ? formik.values[field.name] 
        ? String(formik.values[field.name]) 
        : ''
      : formik.values[field.name]; 
    return (
      <FormField
        field={field}
        value={fieldValue}
        onChange={(name, value) => formik.setFieldValue(name, value)}
        error={error ? String(formik.errors[field.name]) : undefined}
        isReadOnly={ field.name === 'colorCode' || loading || isReadOnly}
        onBlur={formik.handleBlur}
         onAddContract={options?.onAddContract} 
         onAddEstablishment={options?.onAddMainEstablishment}
      />
    );
  };

  const tabs = [
    {
      label: 'Circuit',
      content: (
        <CircuitTabForm
          renderField={renderField}
          mode={mode}
          onEdit={onEdit}
          onClose={(isSaved) => onClose(isSaved)}
        />
      ),
    },
    { label: 'Usagers', content: <CircuitUsager circuitId={formik.values.id} />, disabled: isAddMode },
    { label: 'Avenants', content: <AvenantList circuitId={formik.values.id} />, disabled: isAddMode },
    { label: 'Trajets', content: <CircuittrajetsForm useTabs circuitId={formik.values.id} activationDate={formik.values.lastAmendmentDate}/>, disabled: isAddMode },
    { label: 'Contrat',
      content:
        <CircuitTabForm
          renderField={renderField}
          mode={mode}
          onEdit={onEdit}
          onClose={(isSaved) => onClose(isSaved)}
          fieldsToShow={['contractId','lotIds']}
        />
      },
    { label: 'Chauffeurs', content: <ChauffeurList circuitId={formik.values.id} circuitStartDate={formik.values.startDate} circuitEndDate={formik.values.endDate}   />, disabled: isAddMode },
    { label: 'Documents', content: <CircuitDepotDocumentForm circuitId={formik.values.id}/>, disabled: isAddMode },
  ];

  return (
    <FormContainer titre="Fiche Circuit">
    <FormikProvider value={formik}>
      <form onSubmit={formik.handleSubmit}>
        <Grid container sx={{ width: '100%' }}>
        {formConfig.map((field) => (
          <Grid item xs={12} sm={field.name === 'titled' ? 8 : 4} sx={field.name === 'titled' ? { pl: '1%' }: { pr: '2%'} } key={field.name}>
            {renderField(field)}
          </Grid>
        ))}
        </Grid>
        <TabbedForm tabs={tabs} sx={{mt:4}} />
      </form>
      </FormikProvider>
    </FormContainer>
  );
}