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 congeConfig: TableConfig<IDemandeAbsence> = {
    type: TableType.Conge,
    initialData: [],
    defaultTableHead: ABSENCE_TABLE_COLUMNS,
  };
  
  export function useCongeTable() {
    const tableManager = useTableManager<IDemandeAbsence>(congeConfig);
    const { searchAbsences, absences, loading, error, pagination, createAbsence, updateAbsence } = useAbsenceStoree();
    const [lastParams, setLastParams] = useState<string>('');

    const getApiParams = useCallback(() => {
      const params: ApiParams = {
        page: tableManager.table.page,
        size: tableManager.table.rowsPerPage,
        requestType: 'LEAVE', // Filter for leave requests only
      };

      // 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 '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 'leaveType':
              params.leaveType = 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]
    );

    const handleSave = useCallback(async (conge: IDemandeAbsence, file?: File) => {
      if (conge.id && conge.id !== '') {
        // Update existing
        return await updateAbsence(conge.id, conge, file);
      } else {
        // Create new
        return await createAbsence(conge, file);
      }
    }, [createAbsence, updateAbsence]);

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