import React, { useMemo, useState, useEffect } from 'react';
import { Grid } from '@mui/material';
import { ICircuit } from '@/shared/types/circuit';
import { FormFieldType, TableColumn, TableType } from '@/shared/types/common';
import ActionButtons from '@/shared/components/form/buttons-action';
import { INITIAL_CIRCUIT_DATA } from '@/shared/_mock/_circuit';
import FormField from '@/shared/components/form/form-field';
import { detailsAvenantformFields } from '../utils/form-fields-avenant';
import SignatureField from './signature-field';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

interface CircuitTabContentProps {
  isReadOnly: boolean;
  isEditMode: boolean;
  circuit: ICircuit;
  onEdit?: (updatedCircuit: ICircuit) => void;
  handleSave: () => void;
  onClose: (isSaved: boolean) => void;
  tableHead: TableColumn[];
}

export default function AvenantDetailsForm({
  isReadOnly,
  isEditMode,
  circuit,
  onEdit,
  handleSave,
  onClose,
  tableHead
}: CircuitTabContentProps) {
  const [formData, setFormData] = useState<ICircuit>(circuit);


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

  const memoizedFormFields = useMemo(() => {
    const renderFieldCircuit = (field: FormFieldType<ICircuit>) => (
      <FormField
        field={field}
        value={formData ? formData[field.name] : ''}
        onChange={(name, value) => setFormData((prev) => ({ ...prev, [name]: value }))}
        isReadOnly={field.name ==="etat" ? isReadOnly : true}
      />
    );

    return (
      <>
        {detailsAvenantformFields.map((field) => (
          <Grid
            item
            xs={12}
            sm={4}
            key={field.name}
          >
            {renderFieldCircuit(field)}
          </Grid>
        ))}
      </>
    );
  }, [formData, isReadOnly]);

  return (
    <>
      <ConditionalComponent isValid={isReadOnly && !!onEdit}>
        <EditExportButtons
          onEdit={() => onEdit!(circuit)}
          tooltipTitle={TableType.Avenant}
          dataRow={circuit}
          tableHead={tableHead}
        />
      </ConditionalComponent>
      <Grid container spacing={6} sx={{ pt: 2 }}>
        {memoizedFormFields}
        <Grid item xs={12} sm={6}  sx={{ display: { xs: 'none', sm: 'block' } }} />

        <Grid item xs={12} sm={5}>
          <SignatureField
            isReadOnly={true}
          />
        </Grid>
        <ConditionalComponent isValid={!isReadOnly}>
          <Grid item xs={12}>
            <ActionButtons onSave={handleSave} onCancel={() => onClose(false)} />
          </Grid>
        </ConditionalComponent>
      </Grid>
    </>
  );
}
