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,
  department: "",
  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
});

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 useTreatedAbsenceDriverTable(filters: Search, refreshKey: number) {
  const { processed, fetchProcessed, loading } = useDriverAbsenceStore();

  useEffect(() => {
    fetchProcessed(cleanFilters(filters));
  }, [fetchProcessed, filters, refreshKey]);

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

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

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