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':
            // Extract numeric part from REQ-98 format
            if (filter.value.startsWith('REQ-')) {
              const numericPart = filter.value.replace('REQ-', '');
              if (!isNaN(Number(numericPart))) {
                params.id = numericPart;
              }
            } else {
              // If it's just a number, use it directly
              if (!isNaN(Number(filter.value))) {
                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':
            const searchValue = filter.value.toString().toLowerCase().trim();
            let backendState: string | undefined;
            
            if (searchValue.includes('en attente')) {
              backendState = 'Waiting';
            } else if (searchValue.includes('approve')) {
              backendState = 'Approved';
            } else if (searchValue.includes('refuse')) {
              backendState = 'Rejected';
            }
            
            if (backendState) {
              params.states = backendState;
            }
            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),
  };
}
