import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { IAbsence } from '@/shared/types/absence';
import { DEFAULT_ABSENCE_TABLE_HEAD } from '@/shared/_mock/_absenceUsager';
import { useAbsenceStore } from '@/shared/api/stores/absenceStore';
import { useState, useEffect, useCallback } from 'react';
import React from 'react';

// Interface matching backend parameters
interface AbsencePageFilterParams {
  page?: number;
  size?: number;
  sortBy?: string;
  sortDirection?: 'asc' | 'desc';
  state?: string;
  passengerId?: number;
  receivingMethod?: string;
  establishment?: string;
  departmentName?: string;
  lastName?: string;
  firstName?: string;
  startDateFrom?: string;
  startDateTo?: string;
}

const absenceConfig: TableConfig<IAbsence> = {
  initialData: [],
  defaultTableHead: DEFAULT_ABSENCE_TABLE_HEAD,
};

export const useAbsenceUsagerTable = () => {
  const [params, setParams] = useState<AbsencePageFilterParams>({
    page: 0,
    size: 20,
    sortBy: 'id',
    sortDirection: 'desc'
  });

  const { unprocessedAbsences, processedAbsences, loading, error, fetchUnprocessedAbsences, fetchProcessedAbsences, startExportAbsences } = useAbsenceStore();

  const tableManager = useTableManager<any>({
    ...absenceConfig,
    initialData: unprocessedAbsences || [],
  });

  useEffect(() => {
    if (tableManager.table.rowsPerPage > 0) {
      setParams(prev => ({
        ...prev,
        page: tableManager.table.page,
        size: tableManager.table.rowsPerPage,
      }));
    }
  }, [tableManager.table.page, tableManager.table.rowsPerPage]);

  const isValidDateInput = (value: any): boolean => {
    if (!value || typeof value !== 'string') return false;
    const date = new Date(value);
    return date instanceof Date && !isNaN(date.getTime());
  };

  const isValidFilterValue = (value: any): boolean => {
    return value !== null && value !== undefined && value !== '';
  };

  useEffect(() => {
    const baseParams: AbsencePageFilterParams = {
      page: tableManager.table.page || 0,
      size: tableManager.table.rowsPerPage || 20,
      sortBy: tableManager.table.orderBy || 'id',
      sortDirection: tableManager.table.order.toLowerCase() as 'asc' | 'desc'
    };

    const filterParams: Record<string, any> = {};
    Object.entries(tableManager.filters).forEach(([key, { value }]) => {
      // Handle different field mappings
      switch (key) {
        case 'usager':
          // Split usager into firstName and lastName if it contains a space
          const nameParts = value.split(' ');
          if (nameParts.length > 1) {
            filterParams.firstName = nameParts[0];
            filterParams.lastName = nameParts.slice(1).join(' ');
          } else {
            // If no space, search in both fields
            filterParams.firstName = value;
            filterParams.lastName = value;
          }
          break;
        case 'etablissement':
          filterParams.establishment = value;
          break;
        case 'dateDebut':
          if (isValidDateInput(value)) {
            const date = new Date(value);
            filterParams.startDateFrom = date.toISOString().split('T')[0];
          }
          break;
        case 'dateFin':
          if (isValidDateInput(value)) {
            const date = new Date(value);
            filterParams.startDateTo = date.toISOString().split('T')[0];
          }
          break;
        case 'modeReception':
          filterParams.receivingMethod = value;
          break;
        case 'departement':
          filterParams.departmentName = value;
          break;
        default:
          if (isValidFilterValue(value)) {
            filterParams[key] = value;
          }
      }
    });

    const newParams: AbsencePageFilterParams = {
      ...baseParams,
      ...filterParams
    };

    const paramsChanged = JSON.stringify(newParams) !== JSON.stringify(params);
    if (paramsChanged) {
      setParams(newParams);
      // Call the appropriate fetch function based on the state
      if (newParams.state === 'Unprocessed') {
        fetchUnprocessedAbsences();
      } else {
        fetchProcessedAbsences();
      }
    }
  }, [tableManager.filters, tableManager.table.orderBy, tableManager.table.order]);

  const handlePageChange = (event: React.MouseEvent<HTMLButtonElement> | null, newPage: number) => {
    setParams(prev => ({
      ...prev,
      page: newPage
    }));
  };

  const handleRowsPerPageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const size = parseInt(event.target.value, 10);
    if (!isNaN(size) && size > 0) {
      setParams(prev => ({
        ...prev,
        size,
        page: 0
      }));
    }
  };

  const handleStartExportAbsences = useCallback(async () => {
    try {
      await startExportAbsences();
      return true;
    } catch (error) {
      console.error('Export failed:', error);
      throw error;
    }
  }, [startExportAbsences]);

  return {
    ...tableManager,
    loading,
    error,
    onPageChange: handlePageChange,
    page: params.page,
    onRowsPerPageChange: handleRowsPerPageChange,
    rowsPerPage: params.size,
    sortBy: params.sortBy || 'id',
    sortDirection: params.sortDirection || 'desc',
    filteredData: unprocessedAbsences,
    handleStartExportAbsences,
    dataToExport: unprocessedAbsences
  };
};

