import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { useVehicleIncidentStore } from '@/shared/api/stores/fleet-service/vehicle-incident-store';
import { TableColumn } from '@/shared/types/common';
import { VehicleIncident, VehicleIncidentPageFilterParams } from '@/shared/types/fleet-management/vehicle-incident';
import { useSnackbar } from 'notistack';
import { useEffect, useState } from 'react';

export const DEFAULT_VEHICLE_INCIDENT_TABLE_HEAD: TableColumn[] = [
  { id: 'id', label: 'N°', type: 'text' },
  { id: 'departmentName', label: 'Département', type: 'text' },
  { id: 'incidentDate', label: 'Date', type: 'date' },
  { id: 'vehicleRegistrationPlate', label: 'Véhicule', type: 'text' },
  { id: 'driverName', label: 'Conducteur', type: 'text' },
  { id: 'declarationType', label: 'Déclaration', type: 'text' },
  { id: 'status', label: 'Statut', type: 'statut' },
  { id: 'active', label: 'Actif', type: 'boolean', align: 'center' },
  { id: '', label: 'Action' },
];

const vehicleIncidentConfig: TableConfig<VehicleIncident> = {
  initialData: [],
  defaultTableHead: DEFAULT_VEHICLE_INCIDENT_TABLE_HEAD,
};

export function useVehicleIncidentTable() {
  const { enqueueSnackbar } = useSnackbar();

  const [params, setParams] = useState<VehicleIncidentPageFilterParams>({
    page: 0,
    size: 20,
    orderBy: 'id',
    orderDir: 'desc'
  });

  const {
    error,
    loading,
    vehicleIncidentsPage,
    totalElements,

    fetchVehicleIncidentsPage,
    startCsvExport
  } = useVehicleIncidentStore();

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

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

  const onResetFilters = () => {
    tableManager.handleResetFilters();
    setParams({
      page: 0,
      size: 20,
      orderBy: 'id',
      orderDir: 'desc'
    });
  };

  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: VehicleIncidentPageFilterParams = {
      page: tableManager.table.page || 0,
      size: tableManager.table.rowsPerPage || 20,
      orderBy: tableManager.table.orderBy || 'id',
      orderDir: tableManager.table.order.toLowerCase() as 'asc' | 'desc'
    };

    const filterParams: Record<string, string | number> = {};

    Object.entries(tableManager.filters).forEach(([key, { value }]) => {
      if (key === 'id' && isValidFilterValue(value)) {
        filterParams[key] = Number(value);
      } else if (['incidentDate'].includes(key) && isValidDateInput(value)) {
        const date = new Date(value);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        filterParams[key] = `${year}-${month}-${day}T00:00:00`;
      } else if (isValidFilterValue(value)) {
        filterParams[key] = value;
      }
    });

    const newParams: VehicleIncidentPageFilterParams = {
      ...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 userId = localStorage.getItem('userId');

  const handleStartCsvExportVehicleIncidents = () => {
    if (userId) {
      startCsvExport(userId, params);
    } else {
      enqueueSnackbar("Nous n'avons pas pu identifier l'utilisateur connecté.");
    }
  };

  return {
    ...tableManager,
    loading,
    error,
    totalVehicleIncidents: totalElements || 0,
    onPageChange: handlePageChange,
    page: params.page,
    onRowsPerPageChange: handleRowsPerPageChange,
    rowsPerPage: params.size,
    sortBy: params.orderBy || 'id',
    sortDirection: params.orderDir || 'desc',
    filteredData: vehicleIncidentsPage,
    handleStartCsvExportVehicleIncidents,
    onResetFilters: onResetFilters,
  };
}