// hooks/use-attendance-table.ts
import { useState, useEffect } from 'react';
import { AttendanceSheetPageFilterParams, AttendanceSheetStatus, AttendanceSheet, MonthsString } from '@/shared/types/attendance-sheet';
import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { TableColumn } from '@/shared/types/common';
import { useAttendanceSheetStore } from '@/shared/api/stores/attendanceSheetStore';

export const DEFAULT_ATTENDANCE_TABLE_HEAD: TableColumn[] = [
  { id: 'number', label: 'Numéro', type: 'text' },
  { id: 'circuitName', label: 'Nom du Circuit', type: 'text' },
  { id: 'departmentName', label: 'Nom Département', type: 'text' },
  { id: 'year', label: 'Année', type: 'number' },
  { id: 'month', label: 'Mois', type: 'text' },
  { id: '', label: 'Action' },
];

const attendanceConfig: TableConfig<AttendanceSheet> = {
  initialData: [],
  defaultTableHead: DEFAULT_ATTENDANCE_TABLE_HEAD,
};

export function useAttendanceTable() {
  const [params, setParams] = useState<AttendanceSheetPageFilterParams>({
    page: 0,
    size: 20,
    sortBy: 'number',
    sortDirection: 'desc',
  });

  const { attendanceSheets, totalElements, loading, error, fetchAttendanceSheetsPage } = useAttendanceSheetStore();

  useEffect(() => {
    fetchAttendanceSheetsPage(params);
  }, [params]);

  const tableManager = useTableManager<AttendanceSheet>({
    ...attendanceConfig,
    initialData: attendanceSheets || [],
  });

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

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

  useEffect(() => {
    const baseParams: AttendanceSheetPageFilterParams = {
      page: tableManager.table.page || 0,
      size: tableManager.table.rowsPerPage || 20,
      sortBy: tableManager.table.orderBy || 'number',
      sortDirection: tableManager.table.order.toLowerCase() as 'asc' | 'desc',
    };
    const filterParams: Record<string, string | number> = {};
   Object.entries(tableManager.filters).forEach(([key, { value }]) => {
      if (['year'].includes(key) && isValidFilterValue(value)) {
        filterParams[key] = Number(value);
      } else if (['month'].includes(key) && isValidFilterValue(value)) {
        filterParams[key] = value;
      } else if (['status'].includes(key) && isValidFilterValue(value)) {
        let status: AttendanceSheetStatus;
        switch (value.toLowerCase()) {
          case 'active':
            status = AttendanceSheetStatus.ACTIVE;
            break;
          case 'inactive':
            status = AttendanceSheetStatus.INACTIVE;
            break;
          default:
            status = AttendanceSheetStatus.ACTIVE;
        }
        filterParams[key] = status;
      } else if (isValidFilterValue(value)) {
        filterParams[key] = value;
      }
    });


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

    const paramsChanged = JSON.stringify(newParams) !== JSON.stringify(params);
    if (paramsChanged) {
      setParams(newParams);
    }
  }, [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 refreshData = () => {
    fetchAttendanceSheetsPage(params);
  };

  return {
    ...tableManager,
    loading,
    error,
    totalAttendanceSheets: totalElements || 0,
    onPageChange: handlePageChange,
    page: params.page,
    onRowsPerPageChange: handleRowsPerPageChange,
    rowsPerPage: params.size,
    sortBy: params.sortBy || 'number',
    sortDirection: params.sortDirection || 'desc',
    filteredData: attendanceSheets || [],
    refreshData
  };
}