'use client';

import { useState, useEffect } from 'react';
import { Grid } from '@mui/material';
import FormField from '@/shared/components/form/form-field';
import type { FormFieldType, ModeType } from '@/shared/types/common';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import ActionButtons from '@/shared/components/form/buttons-action';
import type { IFuelHistory } from '@/shared/types/flottes/fuelImport';
import FormContainer from '@/layouts/form/form-container';
import { fuelHistoryFormFields } from '../utils/form-fields-fuel-supplier';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

interface FuelHistoryFormProps {
  fuelHistory: IFuelHistory;
  mode: ModeType;
  onSave: (updatedFuelHistory: IFuelHistory) => void;
  onEdit: (updatedFuelHistory: IFuelHistory) => void;
  onClose: () => void;
}

export default function FuelHistoryForm({
  fuelHistory,
  mode,
  onSave,
  onClose,
  onEdit,
}: FuelHistoryFormProps) {
  const [formData, setFormData] = useState<IFuelHistory>(fuelHistory);

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

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

  const isReadOnly = mode === 'view';

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

  return (
    <FormContainer titre="Historique carburant" hasBorder>
      {isReadOnly ? (
        <EditExportButtons
          onEdit={() => onEdit(fuelHistory)}
          tooltipTitle="l'historique carburant"
        />
      ) : null}

      <form>
        <Grid container spacing={5}>
          {fuelHistoryFormFields.map((field) => (
            <Grid item xs={12} sm={6} key={field.name}>
              {renderField(field)}
            </Grid>
          ))}
          <ConditionalComponent isValid={!isReadOnly}>
            <Grid item xs={12}>
              <ActionButtons onSave={handleSave} onCancel={onClose} mode={mode} />
            </Grid>
          </ConditionalComponent>
        </Grid>
      </form>
    </FormContainer>
  );
}
