import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { IAvenant } from '@/shared/types/circuit';
import { DEFAULT_AVENANT_TABLE_HEAD } from '@/shared/_mock/_avenants';
import { useEffect, useState } from 'react';
import { useAmendmentStore } from '@/shared/api/stores/amendmentStore';
import { AmendmentListDTO } from '@/shared/types/amendment';
import { exportAmendments } from '@/shared/services/amendment-export.service';

// Map API model to internal model
const mapToIAvenant = (amendment: AmendmentListDTO): IAvenant => ({
  id: amendment.id,
  dateApplication: amendment.applicationDate,
  etat: amendment.status,
  codeCircuit: amendment.circuitCode,
  codeAvenant: amendment.amendmentCode,
  intitule: amendment.title,
  objetAvenant: amendment.amendmentPurpose,
  type: amendment.type,
  dateFin: amendment.endDate,
  etablissement: amendment.establishment,
  chauffeur: amendment.driver,
  departement: amendment.company,
  clientDO: amendment.clientDO,
  isActive: amendment.active,
  objet: amendment.purpose
});

export function useAvenantTable() {
  const { getAllAmendments, amendments, loading, error } = useAmendmentStore();
  const [avenantData, setAvenantData] = useState<IAvenant[]>([]);

  useEffect(() => {
    getAllAmendments();
  }, [getAllAmendments]);

  useEffect(() => {
    if (amendments && amendments.content) {
      const mappedData = amendments.content.map(mapToIAvenant);
      setAvenantData(mappedData);
    }
  }, [amendments]);

  const avenantConfig: TableConfig<IAvenant> = {
    initialData: avenantData,
    defaultTableHead: DEFAULT_AVENANT_TABLE_HEAD,
  };

  const tableManager = useTableManager<IAvenant>(avenantConfig);

  // Export handler
  const handleStartExportAvenants = async () => {
    try {
      // Get selected columns from current table head (excluding action column)
      const selectedColumns = tableManager.tableHead
        .filter(col => col.id !== '')
        .map(col => col.id);

      await exportAmendments(tableManager.filters, selectedColumns);
    } catch (error) {
      console.error('Export failed:', error);
      // You might want to show a toast notification here
    }
  };

  return {
    ...tableManager,
    loading,
    error,
    handleStartExportAvenants,
  };
}
