'use client';

import React, { useEffect, useState } from 'react';
import { useFormik } from 'formik';
import FormField from '@/shared/components/form/form-field';
import { FormFieldType, ModeType, TableColumn } from '@/shared/types/common';
import { fuelSupplierFormFields } from '../utils/form-fields-fuel-supplier';
import FormContainer from '@/layouts/form/form-container';
import { fuelSupplierSchema } from '../utils/fuel-supplier-schema';
import TabbedForm from '@/shared/components/tabs/tabbed-form';
import FuelSupplierTab from '../components/Fuel-Supplier-tab';
import { FuelSupplier, FuelSupplierRequestDTO } from '@/shared/types/fleet-management/fuelSupplier';
import { useFuelSupplierStore } from '@/shared/api/stores/fleet-service/fuel-supplier-store';
import { useFuelTypeStore } from '@/shared/api/stores/fleet-service/fuel-type-store';
import { useSnackbar } from 'notistack';

interface FuelSupplierFormProps {
  fuelSupplier: FuelSupplier;
  mode: ModeType;
  onEdit: (updatedFuelSupplier: FuelSupplierRequestDTO) => void;
  onClose: (isSaved: boolean) => void;
  tableHead: TableColumn[];
  setHasUnsavedChanges?: (value: boolean) => void
  updateTabContent?: (tabId: string, newContent: FuelSupplierRequestDTO) => void
  tabId?: string
}

const mapFuelSupplierToRequest = (fuelSupplier: FuelSupplier): FuelSupplierRequestDTO => ({
  id : fuelSupplier.id,
  supplierName: fuelSupplier.supplierName,
  fuelTypeId: fuelSupplier.fuelType?.id || "",
  observation: fuelSupplier.observation,
  isActive: fuelSupplier.active,
});

export default function FuelSupplierForm({
  fuelSupplier,
  mode,
  onClose,
  onEdit,
  tableHead,
  setHasUnsavedChanges,
  updateTabContent,
  tabId,
}: FuelSupplierFormProps) {
  const isReadOnly = mode === 'view';
  const isAddMode = mode === 'add';

  const { enqueueSnackbar } = useSnackbar();

  const [formData, setFormData] = useState<FuelSupplierRequestDTO>({} as FuelSupplierRequestDTO);
  const [fuelTypeOptions, setFuelTypeOptions] = useState<{ value: string; label: string }[]>([]);
  const [fuelTypesFetched, setFuelTypesFetched] = useState(false);

  const {
    fuelSuppliers,
    fetchFuelSupplierById,
    createFuelSupplier,
    updateFuelSupplier,
    fetchAllFuelSuppliers
  } = useFuelSupplierStore();

  const {
    fetchAllFuelTypes
  } = useFuelTypeStore();

  const handleFormSubmit = async (values: FuelSupplierRequestDTO) => {
    if (mode === 'edit') {
      try {
        await updateFuelSupplier(parseInt(fuelSupplier.id), values);
        fetchAllFuelSuppliers()
        onClose(true);
        enqueueSnackbar('Pétrolier modifié avec succès', { variant: 'success' });
      } catch (error: any) {
        enqueueSnackbar(error.message, { variant: 'error' });
        return;
      }
    } else if (mode === 'add' || mode === 'copy') {
      try {
        await createFuelSupplier(values);
        fetchAllFuelSuppliers()
        onClose(true);
        enqueueSnackbar('Pétrolier créé avec succès', { variant: 'success' });
      } catch (error: any) {
        enqueueSnackbar(error.message, { variant: 'error' });
        return;
      }
    }
  };

  const getInitialValues = async () => {
    const allFuelTypes = await fetchAllFuelTypes();
    setFuelTypeOptions(allFuelTypes.map((ft) => ({ value: ft.id.toString(), label: ft.name })));

    if (fuelSupplier?.id && mode !== 'add') {
      const fuelSupplierData = await fetchFuelSupplierById(parseInt(fuelSupplier.id));
      if (fuelSupplierData) {
        setFormData(mapFuelSupplierToRequest(fuelSupplierData));
      }
    } else if (mode === 'add') {
      setFormData({
        id : '',
        supplierName: '',
        fuelTypeId: '',
        observation: '',
        isActive: true,
      });
    } else if (mode === 'copy') {
      setFormData({
        ...mapFuelSupplierToRequest(fuelSupplier),
        supplierName: `Copie de ${fuelSupplier.supplierName}`,
      });
    } else {
      setFormData(mapFuelSupplierToRequest(fuelSupplier));
    }
  }

  useEffect(() => {
  if (!fuelTypesFetched) {
    getInitialValues();
    setFuelTypesFetched(true); // Set to true after first fetch
  }
}, [fuelTypesFetched]);

  const formik = useFormik<FuelSupplierRequestDTO>({
    initialValues: formData,
    validationSchema: fuelSupplierSchema,
    onSubmit: (values) => {
      handleFormSubmit(values)
      onClose(true)
    },
    enableReinitialize: true
  })

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

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

  const baseFields = fuelSupplierFormFields(fuelTypeOptions);

  const tabs = [
    {
      label: 'Détails pétrolier',
      content: (
        <FuelSupplierTab
          renderField={renderField}
          baseFields={baseFields}
          isReadOnly={isReadOnly}
          formik={formik}
          onEdit={onEdit}
          onSave={() => {
            formik.validateForm().then(() => {
              formik.submitForm();
            });
          }}
          onClose={onClose}
          tableHead={tableHead}
          mode={mode}
        />
      ),
    },
  ];

  return (
    <FormContainer titre="Fiche Pétrolier">
      <TabbedForm tabs={tabs} />
    </FormContainer>
  );
}