"use client"

import { useMemo } from "react"
import { type TableConfig, useTableManager } from "@/hooks/use-table-manager"
import { DriverAbsenceStatus, type IDriverAbsence } from "@/shared/types/driver-absence"
import { _absencesDriver, DEFAULT_ABSENCE_DRIVER_TABLE_HEAD } from "@/shared/_mock/_absenceDriver"
import React from "react"

const getNonTraitedAbsences = (absences: IDriverAbsence[]): IDriverAbsence[] => {
  return absences.filter(
    (absence) => absence.statut === DriverAbsenceStatus.EnCours || absence.statut === DriverAbsenceStatus.NonTraite,
  )
}

const getTraitedAbsences = (absences: IDriverAbsence[]): IDriverAbsence[] => {
  return absences.filter(
    (absence) => absence.statut === DriverAbsenceStatus.Valide || absence.statut === DriverAbsenceStatus.Rejete,
  )
}

export function useAbsenceDriverTable(isNonTraite: boolean) {
  const [data, setData] = React.useState(_absencesDriver);

  const filteredData = useMemo(() => {
    return isNonTraite ? getNonTraitedAbsences(data) : getTraitedAbsences(data)
  }, [isNonTraite, data])
  const filteredTraiteData = useMemo(() => {
    return getTraitedAbsences(data);
  }, [data]);
  const handleStatusChange = (row: IDriverAbsence, newStatus: string, field: keyof IDriverAbsence) => {
    setData(prevData => 
      prevData.map(absence => 
        absence.id === row.id 
          ? { ...absence, [field]: newStatus }
          : absence
      )
    );
  };
  const absenceDriverConfig: TableConfig<IDriverAbsence> = {
    initialData: filteredData,
    defaultTableHead: DEFAULT_ABSENCE_DRIVER_TABLE_HEAD(isNonTraite),
  }

  const tableManager = useTableManager<IDriverAbsence>(absenceDriverConfig);

  return {
    ...tableManager,
    handleStatusChange,
    filteredTraiteData,
    filteredData,
  }
}
