import React, { useMemo, useState, useEffect } from 'react';
import { Grid } from '@mui/material';
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 '@/shared/sections/avenant/components/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';

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

export default function CircuitAvenantDetailsForm({
  isReadOnly,
  isEditMode,
  avenant,
  onEdit,
  handleSave,
  onClose,
  tableHead
}: CircuitTabContentProps) {

  console.log('circuit', avenant);
  const [formData, setFormData] = useState<AmendmentCircuit>(avenant);


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

  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
          onEdit={() => onEdit!(avenant)}
          tooltipTitle={TableType.Avenant}
          dataRow={avenant}
          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>
    </>
  );
}
