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';
import { enqueueSnackbar } from 'notistack';

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,
    maxAbsencesCount,
    fetchMaxAbsencesCount
  } = 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(() => {
    fetchMaxAbsencesCount();
  }, []);

  useEffect(() => {
    const smartSize = maxAbsencesCount || 1000;
    
    const baseParams: AbsencePageFilterParams = {
      page: 0,
      size: smartSize,
      sortBy: 'startDate',
      sortDirection: 'desc',
      state: isProcessed ? ['Processed', 'Cancelled'] : ['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 'id':
          filterParams.passengerId = parseInt(value);
          break;
      }
    });

    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, isProcessed, maxAbsencesCount]);

  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();
      enqueueSnackbar('Export des absences lancé avec succès.', { variant: 'success' });
      return true;
    } catch (error) {
      console.error('Export failed:', error);
      enqueueSnackbar("Échec du lancement de l'export des absences.", { variant: '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
  };
};

