'use client';

import { StyledTextField } from '@/shared/theme/css';
import { Grid, InputAdornment } from '@mui/material';
import FontAwesome from '@/shared/components/fontawesome';
import SvgColor from '@/shared/components/svg-color';
import { faHashtag } from '@fortawesome/free-solid-svg-icons';
import { useEffect, useState } from 'react';
import CircuitTabForm from '../components/circuit-form/circuit-form';
import CircuittrajetsForm from '../components/circuit-form/trajet/trajets-list';
import { ICircuit } 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 DocumentForm from '../../../components/documents/documents-form';
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 { useFormik } from 'formik';
import { circuitSchema } from '../utils/circuit-validation';
import { formConfig } from '../utils/form-fields-circuit';

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

export default function CircuitForm({ circuit, mode, onSave, onClose, onEdit, updateTabContent, tabId }: CircuitFormProps) {

  const formik = useFormik<ICircuit>({
    initialValues: circuit,
    validationSchema: circuitSchema,
    onSubmit: (values) => {
      onSave(values);
      onClose(true);
    },
    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 isReadOnly = mode === 'view';
  const isAddMode = mode === 'add';
  const isEditMode = mode === 'edit';

  const renderField = (field: FormFieldType<ICircuit>) => {
    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: 'Circuit',
      content: (
        <CircuitTabForm
          isReadOnly={isReadOnly}
          isEditMode={isEditMode}
          circuit={circuit}
          onEdit={onEdit}
          onClose={(isSaved) => onClose(isSaved)}
          formik={formik}
        />
      ),
    },
    { label: 'Usagers', content: <CircuitUsager /> },
    { label: 'Trajets', content: <CircuittrajetsForm useTabs/>, disabled: isAddMode },
    { label: 'Avenants', content: <AvenantList />, disabled: isAddMode },
    { label: 'Contrats', content: <ContratForm />, disabled: isAddMode },
    { label: 'Chauffeurs', content: <ChauffeurList />, disabled: isAddMode },
    { label: 'Documents', content: <DocumentForm documents={_documents}/>, disabled: isAddMode },
  ];

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