'use client';

import React, { useEffect } from 'react';
import { Grid } from '@mui/material';
import { useFormik } from 'formik';
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 { ITankerType } from '@/shared/types/flottes/fuelImport';
import FormContainer from '@/layouts/form/form-container';
import { supplierTypeFormFields } from '../utils/form-fields-supplier-type';
import FuelHistoryList from '../components/fuel-history-new-view';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { supplierTypeSchema } from '../utils/supplier-type-schema';

interface SupplierTypeFormProps {
  supplierType: ITankerType;
  mode: ModeType;
  onSave: (updatedSupplierType: ITankerType) => void;
  onEdit: (updatedSupplierType: ITankerType) => void;
  onClose: () => void;
  setHasUnsavedChanges?: (value: boolean) => void
  updateTabContent?: (tabId: string, newContent: ITankerType) => void
  tabId?: string
}

export default function SupplierTypeForm({
  supplierType,
  mode,
  onSave,
  onClose,
  onEdit,
  setHasUnsavedChanges,
  updateTabContent,
  tabId,
}: SupplierTypeFormProps) {
  const isReadOnly = mode === 'view';

  const formik = useFormik<ITankerType>({
    initialValues: supplierType,
    validationSchema: supplierTypeSchema,
    onSubmit: (values) => {
      onSave(values);
      if (setHasUnsavedChanges) setHasUnsavedChanges(false)
      onClose();
    },
  });

  useEffect(() => {
    if (updateTabContent && tabId && (mode !== "view")) {
      updateTabContent(tabId, formik.values)
    }
  }, [formik.values, updateTabContent, tabId, mode])


  const renderField = (field: FormFieldType<ITankerType>) => (
    <FormField
      field={field}
      value={formik.values[field.name as keyof ITankerType]}
      onChange={(name, value) => formik.setFieldValue(name, value)}
      error={
        formik.touched[field.name as keyof ITankerType]
          ? (formik.errors[field.name as keyof ITankerType] as string | undefined)
          : undefined
      }
      onBlur={formik.handleBlur}
      isReadOnly={isReadOnly}
    />
  );

  return (
    <FormContainer titre="Type de fournisseur">
      <ConditionalComponent isValid={isReadOnly}>
        <EditExportButtons
          onEdit={() => onEdit(formik.values)}
          tooltipTitle="le type de fournisseur"
        />
      </ConditionalComponent>

      <form onSubmit={formik.handleSubmit}>
        <Grid container spacing={4}>
          {supplierTypeFormFields.map((field) => (
            <Grid item xs={12} sm={4} key={field.name}>
              {renderField(field)}
            </Grid>
          ))}
          <ConditionalComponent isValid={!isReadOnly}>
            <Grid item xs={12}>
              <ActionButtons
                onSave={() => {
                  formik.validateForm().then((errors) => {
                    formik.submitForm();
                  });
                }}
                onCancel={onClose}
                mode={mode}
              />
            </Grid>
          </ConditionalComponent>

          <Grid item xs={12} key={'carte_carburant'}>
            <FuelHistoryList supplierType={formik.values}></FuelHistoryList>
          </Grid>
        </Grid>
      </form>
    </FormContainer>
  );
}
