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 SignatureField from './signature-field';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { AmendmentCircuit } from '@/shared/types/ammendment-circuit';
import { detailsAvenantformFields } from '../../circuit/components/circuit-form/avenant/utils/form-fields-avenant';

interface CircuitTabContentProps {
  isReadOnly: boolean;
  isEditMode: boolean;
  circuit: AmendmentCircuit;
  onEdit?: (updatedCircuit: AmendmentCircuit) => 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<AmendmentCircuit>(circuit);


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

  const memoizedFormFields = useMemo(() => {
    const renderFieldCircuit = (field: FormFieldType<AmendmentCircuit>) => (
      <FormField
        field={field}
        value={formData ? formData[field.name] : ''}
        onChange={(name, value) => setFormData((prev) => ({ ...prev, [name]: value }))}
        isReadOnly={field.name ==="circuitState" ? 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
          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>
    </>
  );
}
