'use client';

import React, { useEffect, useState } from 'react';
import {
  Typography,
  Grid,
  Box,
} from '@mui/material';
import { useFormik, FormikProvider } from 'formik';
import { _CONTRACT_STATUS } from '../../../_mock/_Contrat';
import { centerFlexColumn } from '@/shared/theme/css';
import FormField from '@/shared/components/form/form-field';
import { FormFieldType, ModeType, TableColumn } from '@/shared/types/common';
import FormContainer from '@/layouts/form/form-container';
import TabbedForm from '@/shared/components/tabs/tabbed-form';
import UsagerTabForm from '../components/usager-form/usager-form';
import DepotDocumentForm from '../components/usager-form/depot-document';
import AutresInterlocuteursForm from '../components/usager-form/autres-interlocuteurs';
import SuiviDossierForm from '../components/usager-form/suivi-dossier';
import RepresentantTabs from '../components/usager-form/representant/representant-tabs';
import AvenantsHorairesList from '../components/usager-form/avenants-horaires/avenants-horaires-list';
import { usagerSchema } from '../utils/usager-validation';
import { IPassengerList, Representative } from '@/shared/types/passenger';
import { calculateAge, mainPassengerFormFields } from '../utils/form-fields-usager';
import { usePassengerStore } from '@/shared/api/stores/passengerStore';
import { enqueueSnackbar } from 'notistack';

interface TrajetFormProps {
  usager: IPassengerList;
  mode: ModeType;
  onSave: (updatedUsager: IPassengerList) => void;
  onEdit: (updatedUsager: IPassengerList, replaceCurrentTab?: boolean) => void;
  onClose: (isSaved: boolean) => void;
  tableHead: TableColumn[];
  updateTabContent: (tabId: string, content: IPassengerList) => void;
  tabId: string;
  hasUnsavedChanges?: boolean;
  markTabAsSaved: (tabId: string, content: IPassengerList) => void;
  setTabReplaceCurrentTab: (tabId: string, replaceCurrentTab: boolean) => void;
  }

export default function UsagerForm({ usager, mode, onSave, onClose, onEdit, tableHead, updateTabContent, tabId, hasUnsavedChanges, markTabAsSaved, setTabReplaceCurrentTab }: TrajetFormProps) {
  const isReadOnly = mode === 'view';
  const isEditMode = mode === 'edit';
  const isAddMode = mode === 'add';

  const { addPassenger, loading, updatePassenger } = usePassengerStore();

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

  const formik = useFormik<IPassengerList>({
    initialValues: usager,
    enableReinitialize:true,
    validationSchema: usagerSchema,
    onSubmit: (values) => {
      handleFormSubmit(values)
    },
  });

  const handleEdit = () => {
    onEdit(formik.values);
  };

  const handleSave = () => {
    formik.validateForm().then((errors) => {
      formik.submitForm();
    });
  };

  const handleCancel = () => {
    onClose(false);
  };

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


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

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

  const renderField = (field: FormFieldType<IPassengerList>) => {
    const error = formik.touched[field.name] && formik.errors[field.name];
    return (
      <FormField
        field={field}
        value={
          field.name === 'idDepartment' ? String(formik.values[field.name]) : formik.values[field.name]
        }
        onChange={(name, value) => {
          formik.setFieldValue(name, value);
          if (name === 'birthDate') {
            formik.setFieldValue('age', calculateAge(value) || 0);
          }
        }}
        error={error ? String(formik.errors[field.name]) : undefined}
        isReadOnly={field.name === 'startTransport' && isEditMode ? true : loading || isReadOnly}
        onBlur={formik.handleBlur}
      />
    );
  };

  const tabs = [
    {
      label: 'Usagers',
      content: <UsagerTabForm
        renderField={renderField}
        mode={mode}
        usager={usager}
        onEdit={handleEdit}
        onClose={handleCancel}
        handleSave={handleSave}
        tableHead={tableHead}
        loading={loading}
      />,
    },
    {
      label: 'Représentant, Adresses et Circuits',
      content: (
        <RepresentantTabs
          withContact
          onSave={handleSave}
          loading={loading}
          onClose={handleCancel}
          onEdit={handleEdit}
          mode={mode}
        />
      ),
    },
    {
      label: 'Depot de documents',
      content: <DepotDocumentForm idUser={formik.values.id} />,
      disabled: isAddMode,
    },
    {
      label: 'Avenants horaires',
      content: <AvenantsHorairesList key={formik.values.id} usager={usager} />,
      disabled: isAddMode,
    },
    {
      label: 'Autres interlocuteurs',
      content: (
        <AutresInterlocuteursForm
          mode={mode}
          onEdit={handleEdit}
          onSave={handleSave}
          onCancel={handleCancel}
          loading={loading}
        />
      ),
    },
    {
      label: 'Suivi de dossier',
      content: <SuiviDossierForm usager={usager} />,
    },
  ];

  return (
    <FormContainer titre="Fiche Usager">
      <FormikProvider value={formik}>
        <form onSubmit={formik.handleSubmit}>
          <Grid container spacing={4} sx={{ width: '100%' }}>
            {mainPassengerFormFields.map((usager) => (
              <Grid
                item
                sx={centerFlexColumn}
                xs={12}
                sm={usager.name === 'civility' ? 3.2 : 3.5}
                key={usager.name}
              >
                {renderField(usager)}
              </Grid>
            ))}
            <Grid
              sx={centerFlexColumn}
              item
              xs={12}
              sm={1.8}
            >
              <Box display="flex" alignItems="center" gap={1}>
                <Typography sx={{ color: (theme) => theme.palette.primary.main }}>Age</Typography>
                <Typography>
                  {formik.values.age ? `${formik.values.age} ans` : '-'}
                </Typography>
              </Box>
            </Grid>
          </Grid>
          <TabbedForm 
            tabs={tabs} 
            sx={{ mt: 4 }} 
            showNavigationButtons 
          />
        </form>
      </FormikProvider>
    </FormContainer>
  );
}
