'use client';

import React, { useEffect } from 'react';
import {
  Typography,
  Grid,
  Box,
} from '@mui/material';
import { useFormik } 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';

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 isAddMode = mode === 'add';

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

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

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

  const renderField = (field: FormFieldType<IPassengerList>) => {
    const error = formik.touched[field.name] && formik.errors[field.name];
    return (
      <FormField
        field={field}
        value={formik.values[field.name]}
        onChange={(name, value) => formik.setFieldValue(name, value)}
        error={error ? String(formik.errors[field.name]) : undefined}
        isReadOnly={isReadOnly}
        onBlur={formik.handleBlur}
      />
    );
  };

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

  return (
    <FormContainer titre="Fiche Usager">
      <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['birthDate'] ? `${calculateAge(formik.values['birthDate'])} ans` : '-'}
              </Typography>
            </Box>
          </Grid>
        </Grid>
        <TabbedForm tabs={tabs} sx={{mt:4}} showNavigationButtons/>
      </form>
    </FormContainer>
  );
}
