import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { ABSENCE_TABLE_COLUMNS } from '@/shared/_mock/_absences';
import { TableType } from '@/shared/types/common';
import { ApiParams, IDemandeAbsence } from '@/shared/types/leave';
import { useAbsenceStoree } from '@/shared/api/stores/absenceStore';
import { useEffect, useState, useCallback } from 'react';



const absenceConfig: TableConfig<IDemandeAbsence> = {
  type: TableType.DemandeAbsence,
  initialData: [],
  defaultTableHead: ABSENCE_TABLE_COLUMNS,
};

export function useCongeTable() {
  const tableManager = useTableManager<IDemandeAbsence>(absenceConfig);
  const { searchAbsences, absences, loading, error, pagination } = useAbsenceStoree();
  const [lastParams, setLastParams] = useState<string>('');

  const getApiParams = useCallback(() => {
    const userId = localStorage.getItem('userId');
    const params: ApiParams = {
      userId: userId ? parseInt(userId) : undefined,
      page: tableManager.table.page,
      size: tableManager.table.rowsPerPage,
    };

    // Add sorting if present
    if (tableManager.table.orderBy && tableManager.table.order) {
      const orderBy =
        tableManager.table.orderBy === 'requestNumber' ? 'id' : tableManager.table.orderBy;
      params.sort = [`${orderBy},${tableManager.table.order.toLowerCase()}`];
    }

    // Map filters to API params
    Object.entries(tableManager.filters || {}).forEach(([key, filter]) => {
      if (filter?.value) {
        switch (key) {
          case 'requestNumber':
            params.id = filter.value;
            break;
          case 'submissionDate':
            params.submittedAt = new Date(filter.value).toISOString().split('T')[0];
            break;
          case 'requestType':
            params.requestType = filter.value === 'Congé' ? 'LEAVE' : 'ABSENCE';
            break;
          case 'startDate':
            params.startDate = new Date(filter.value).toISOString().split('T')[0];
            break;
          case 'endDate':
            params.endDate = new Date(filter.value).toISOString().split('T')[0];
            break;
          case 'status':
            switch (filter.value) {
              case 'En attente':
                params.state = 'Waiting';
                break;
              case 'Approuvée':
                params.state = 'Approved';
                break;
              case 'Refusée':
                params.state = 'Rejected';
                break;
            }
            break;
          case 'processDate':
            params.processedAt = new Date(filter.value).toISOString().split('T')[0];
            break;
          case 'daysCount':
            const days = parseInt(filter.value);
            if (!isNaN(days)) {
              params.numberOfDays = days;
            }
            break;
          case 'type':
            params.leaveType = filter.value;
            break;
          case 'absenceType':
            params.absenceType = filter.value;
            break;
        }
      }
    });

    return params;
  }, [
    tableManager.filters,
    tableManager.table.order,
    tableManager.table.orderBy,
    tableManager.table.page,
    tableManager.table.rowsPerPage,
  ]);

  useEffect(() => {
    const params = getApiParams();
    const paramsString = JSON.stringify(params);
    if (paramsString !== lastParams) {
      setLastParams(paramsString);
      searchAbsences(params, params.page, params.size, params.sort);
    }
  }, [getApiParams, lastParams, searchAbsences]);

  const handlePageChange = useCallback(
    (event: unknown, newPage: number) => {
      tableManager.table.onChangePage(event, newPage);
    },
    [tableManager.table]
  );

  const handleRowsPerPageChange = useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      tableManager.table.onChangeRowsPerPage(event);
    },
    [tableManager.table]
  );

  return {
    ...tableManager,
    filteredData: absences || [],
    loading,
    error,
    onPageChange: handlePageChange,
    page: tableManager.table.page,
    onRowsPerPageChange: handleRowsPerPageChange,
    rowsPerPage: tableManager.table.rowsPerPage,
    count: pagination.total || 0,
    pagination,
    refreshData: useCallback(() => {
      const params = getApiParams();
      searchAbsences(params, params.page, params.size, params.sort);
    }, [getApiParams, searchAbsences]),
    notFound: !loading && (!absences || absences.length === 0),
  };
}
