'use client';

import { Grid } from '@mui/material';
import { useEffect, useState } from 'react';
import { AmendmentCircuit } from '@/shared/types/ammendment-circuit';
import FormField from '@/shared/components/form/form-field';
import { FormFieldType, ModeType, TableColumn } from '@/shared/types/common';
import TabbedForm from '@/shared/components/tabs/tabbed-form';
import FormContainer from '@/layouts/form/form-container';
import CircuittrajetsForm from '../../circuit/components/circuit-form/trajet/trajets-list';
import AvenantDetailsForm from '../components/avenant-details';
import AvenantHoraireForm from '../components/avenant-horaire';
import { mainAvenantformFields } from '../../circuit/components/circuit-form/avenant/utils/form-fields-avenant';


interface CircuitFormProps {
  avenant: AmendmentCircuit;
  isMainTable?: boolean;
  mode: ModeType;
  onSave?: (updatedContract: AmendmentCircuit) => void;
  onEdit?: (updatedContract: AmendmentCircuit) => void;
  onClose: (isSaved: boolean) => void;
  hasBorder?:boolean;
  tableHead: TableColumn[];
  updateTabContent?: (tabId: string, newContent: AmendmentCircuit) => void
  tabId?: string
}

export default function AvenantForm({ avenant, mode, onSave, onClose, onEdit, isMainTable, hasBorder, tableHead, updateTabContent, tabId }: CircuitFormProps) {
  const [formData, setFormData] = useState<AmendmentCircuit>(avenant);
  const isReadOnly = mode === 'view';
  const isEditMode = mode === 'edit';

  const handleEdit = () => {
    if (onEdit) {
      onEdit(formData);
    }
    onClose(true);
  };

  const handleSave = () => {
    if (onSave) {
      onSave(formData);
    }
    onClose(true);
  };

  useEffect(() => {
    if (updateTabContent && tabId && (mode !== "view")) {
      updateTabContent(tabId, formData)
    }
  }, [formData, updateTabContent, tabId, mode])

  const renderField = (field: FormFieldType<AmendmentCircuit>) => (
    <FormField
      field={field}
      value={formData[field.name]}
      onChange={(name, value) => setFormData((prev) => ({ ...prev, [name]: value }))}
      isReadOnly={true}
    />
  );

  const tabs = [
    {
      label: isMainTable ? 'Details avenant' : 'Circuit',
      content: <AvenantDetailsForm
        tableHead={tableHead}
        isReadOnly={isReadOnly}
        isEditMode={isEditMode}
        circuit={formData}
        {...(onEdit && { onEdit: handleEdit })}
        onClose={(isSaved) => onClose(isSaved)}
        handleSave={handleSave}
      />
    },
    {
      label: 'Trajets',
      content: <CircuittrajetsForm circuitId={formData.code} />
    },
    { label: 'Horaires',  content: (
      <AvenantHoraireForm
        onEdit={handleEdit}
        onClose={(isSaved) => onClose(isSaved)}
        onSave={handleSave}
        mode={mode}
        avenant={formData}
      />
    )},
   ];

  return (
    <FormContainer titre="Fiche d'un avenant" isSousElemnt={!isMainTable} hasBorder={hasBorder}>
      <form>
        <Grid container spacing={6} >
          {mainAvenantformFields.map((avenantField) => (
            <Grid
              item
              xs={12}
              sm={avenantField.name === 'code' ? 4 : 8}
              key={avenantField.name}
            >
              {renderField(avenantField)}
            </Grid>
          ))}
        </Grid>
        <TabbedForm tabs={tabs} sx={{mt:4}}  />
      </form>
    </FormContainer>
  );
}
