import { useEffect, useMemo } from "react";
import { useTableManager, TableConfig } from "@/hooks/use-table-manager";
import { useDriverAbsenceStore, DriverAbsenceList, Search } from "@/shared/api/stores/driverAbsenceStore";
import { IDriverAbsence } from "@/shared/types/driver-absence";
import { DEFAULT_ABSENCE_DRIVER_TABLE_HEAD } from "@/shared/_mock/_absenceDriver";
import { BinaryQuestion } from "@/shared/types/trajet";

const map = (a: DriverAbsenceList): IDriverAbsence => ({
  id: a.id.toString(),
  driverName: a.driverName,
  chauffeur: a.driverName,
  typeAbsence: a.absenceType,
  dateDebut: a.startDate,
  dateFin: a.endDate,
  chauffeurAffecte: a.isAssigned ? BinaryQuestion.Oui : BinaryQuestion.Non,
  modeReception: a.receptionMode,
  nombreHeures: a.nbHours?.toString() ?? "",
  autorisePar: a.authorizedBy?.toString() ?? "",
  validePar: a.validatedBy?.toString() ?? "",
  statut: a.status,
  justificatif: new File([], a.supportingDocumentId?.toString() ?? ''),
  supportingDocumentId: a.supportingDocumentId,
  driver: a.driver?.id ? a.driver : undefined,
  department: ""
});

function cleanFilters(filters: Record<string, any>) {
  const cleaned: Record<string, any> = {};
  Object.keys(filters).forEach((key) => {
    const value = filters[key];
    if (
      value !== undefined &&
      value !== null &&
      value !== ""
    ) {
      cleaned[key] = value;
    }
  });
  return cleaned;
}

export function useUntreatedAbsenceDriverTable(filters: Search, refreshKey: number) {
  const { unprocessed, fetchUnprocessed, loading } = useDriverAbsenceStore();

  useEffect(() => {
    console.log("Fetching unprocessed absences with filters:", cleanFilters(filters));
    
    fetchUnprocessed(cleanFilters(filters));
  }, [fetchUnprocessed, filters, refreshKey]);

  const rows = useMemo(() => unprocessed.map(map), [unprocessed]);

  const config: TableConfig<IDriverAbsence> = {
    initialData: rows,
    defaultTableHead: DEFAULT_ABSENCE_DRIVER_TABLE_HEAD(false),
  };

  return { ...useTableManager<IDriverAbsence>(config), rows, loading };
}

