'use client';

import React, { useEffect } 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 } 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) => void;
  onClose: (isSaved: boolean) => void;
  tableHead: TableColumn[];
  updateTabContent: (tabId: string, content: IPassengerList) => void;
  tabId: string;
}

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

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

  const handleFormSubmit = async (values: IPassengerList) => {
    try {
      if (isEditMode) {
        await updatePassenger(values);
        enqueueSnackbar("Usager modifié avec succès", { variant: 'success' });
      } else if (mode === 'add' || mode === 'copy') {
        await addPassenger(values);
        enqueueSnackbar("Usager ajouté avec succès", { variant: 'success' });
      }
      onClose(true);
    } catch (error: any) {
      enqueueSnackbar(error.message, { variant: 'error' });
    }
  };

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

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

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

  const handleCancel = () => {
    formik.resetForm();
    onClose(false);
  };

  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' || field.name === 'idEstablishment' ? 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={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}
        />
      ),
    },
    {
      label: 'Depot de documents',
      content: <DepotDocumentForm usager={usager} />,
    },
    {
      label: 'Avenants horaires',
      content: <AvenantsHorairesList key={usager.id} usager={usager} />,
    },
    {
      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>
  );
}
