'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, SaveCircuit } from '@/shared/types/circuit';
import AvenantList from '../components/circuit-form/avenant/avenants-list';
import ContratForm from '../components/circuit-form/contract/contracts-form';
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 DepotDocumentForm from '../../usager/components/usager-form/depot-document';

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

export default function CircuitForm({ circuit, mode, onSave, onClose, onEdit, updateTabContent, tabId, markTabAsSaved, hasUnsavedChanges }: 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, ...valuesWithoutId } = values;
        await addCircuit(valuesWithoutId as SaveCircuit);
        enqueueSnackbar("Circuit ajouté avec succès", { variant: 'success' });
        onClose(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>) => {
    const error = formik.touched[field.name] && formik.errors[field.name];
    const shouldConvertToString = [
      'mainDriver', 
      'mainEstablishment', 
      'timeTolerance'
    ].includes(field.name);
    const fieldValue = shouldConvertToString ? 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={loading || isReadOnly}
        onBlur={formik.handleBlur}
      />
    );
  };

  const tabs = [
    {
      label: 'Circuit',
      content: (
        <CircuitTabForm
          renderField={renderField}
          mode={mode}
          circuit={circuit}
          onEdit={onEdit}
          onClose={(isSaved) => onClose(isSaved)}
        />
      ),
    },
    { label: 'Usagers', content: <CircuitUsager circuitId={circuit.id} />, disabled: isAddMode },
    { label: 'Avenants', content: <AvenantList />, disabled: isAddMode },
    { label: 'Trajets', content: <CircuittrajetsForm useTabs/>, disabled: isAddMode },
    { label: 'Contrats', content: <ContratForm />, disabled: isAddMode },
    { label: 'Chauffeurs', content: <ChauffeurList />, disabled: isAddMode },
    { label: 'Documents', content: <DepotDocumentForm idUser={''}/>, 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>
  );
}
