'use client';

import { Grid } from '@mui/material';
import { useEffect, useState } from 'react';
import { IAvenant } from '@/shared/types/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 { mainAvenantformFields } from './utils/form-fields-avenant';
import CircuittrajetsForm from '@/shared/sections/circuit/components/circuit-form/trajet/trajets-list';
import { _circuits } from '@/shared/_mock/_circuit';
import AvenantHoraireForm from '@/shared/sections/avenant/components/avenant-horaire';
import { AmendmentCircuit } from '@/shared/types/ammendment-circuit';
import CircuitAvenantHoraireForm from './components/avenant-horaire';
import CircuitAvenantDetailsForm from './components/avenant-details';


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
  circuitId: string;
}


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

  useEffect(() => {
    setFormData(avenant);
  }, [avenant]);

  const isReadOnly = mode === 'view';
  const isEditMode = mode === 'edit';

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

  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: <CircuitAvenantDetailsForm tableHead={tableHead} isReadOnly={isReadOnly} isEditMode={isEditMode} avenant={avenant} {...(onEdit && { onEdit: handleEdit })}
      onClose={(isSaved) => onClose(isSaved)} handleSave={handleSave} />
    },
    { label: 'Trajets', content: <CircuittrajetsForm circuitId={circuitId} amendmentId={avenant.id} activationDate={avenant.startDate} />  },
    { label: 'Horaires',  content: (
      <CircuitAvenantHoraireForm
        onEdit={handleEdit}
        onClose={(isSaved) => onClose(isSaved)}
        onSave={handleSave}
        mode={mode}
        avenant={avenant}
      />
    )},
   ];
  return (
    <FormContainer titre="Fiche d'un avenant" isSousElemnt={!isMainTable} hasBorder={hasBorder}>
      <form>
      <Grid container spacing={6} >
          {mainAvenantformFields.map((avenant) => (
            <Grid
              item
              xs={12}
              sm={avenant.name === 'code' ? 4 : 8}
              key={avenant.name}
            >
              {renderField(avenant)}
            </Grid>
          ))}
        </Grid>
        <TabbedForm tabs={tabs} sx={{mt:4}}  />
      </form>
    </FormContainer>
  );
}
