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 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 = (isProcessed = false) => {
  const [params, setParams] = useState<AbsencePageFilterParams>({
    page: 0,
    size: 30,
    sortBy: 'startDate',
    sortDirection: 'desc',
    state: ['Unprocessed', 'In_progress']
  });

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

  const tableManager = useTableManager<any>({
    ...absenceConfig,
    initialData: isProcessed ? processedAbsences || [] : 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 || 50,
      sortBy: 'startDate', 
      sortDirection: tableManager.table.order.toLowerCase() as 'asc' | 'desc',
      state: ['Unprocessed', 'In_progress']
    };

    const filterParams: Record<string, any> = {};
    Object.entries(tableManager.filters).forEach(([key, { value }]) => {
      switch (key) {
        case 'usager':
          const nameParts = value.trim().split(' ');
          if (nameParts.length >= 2) {
            filterParams.firstName = nameParts[0];
            filterParams.lastName = nameParts.slice(1).join(' ');
          } else {
            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);
      if (isProcessed) {
        fetchProcessedAbsences(newParams);
      } else {
        fetchUnprocessedAbsences(newParams);
      }
    }
  }, [tableManager.filters, tableManager.table.orderBy, tableManager.table.order, tableManager.table.page, tableManager.table.rowsPerPage]);

  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: isProcessed ? processedAbsences : unprocessedAbsences,
    handleStartExportAbsences,
    dataToExport: isProcessed ? processedAbsences : unprocessedAbsences,
    totalCount: isProcessed ? processedTotalElements : unprocessedTotalElements
  };
};

