import { type TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { useServiceProviderStore } from '@/shared/api/stores/fleet-service/service-provider-store';
import { TableColumn } from '@/shared/types/common';
import { ServiceProvider, ServiceProviderPageFilterParams } from '@/shared/types/fleet-management/service-provider';
import { useEffect, useState } from 'react';
import { useSnackbar } from 'notistack';

export const DEFAULT_SERVICE_PROVIDER_TABLE_HEAD: TableColumn[] = [
  { id: 'id', label: 'Id', type: 'text' },
  { id: 'name', label: 'Nom du fournisseur', type: 'text' },
  { id: 'coverageZone', label: 'Zone de couverture', type: 'text' },
  { id: 'intervention', label: 'Intervention', type: 'text' },
  { id: 'interventionType', label: 'Type d\'intervention', type: 'text' },
  { id: 'amount', label: 'Prix', type: 'number' },
  { id: 'action', label: 'Action', align: 'center' },
];

const serviceProviderConfig: TableConfig<ServiceProvider> = {
  initialData: [],
  defaultTableHead: DEFAULT_SERVICE_PROVIDER_TABLE_HEAD,
};

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

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

  const {
    loading,
    error,
    serviceProvidersPage,
    totalElements,
    fetchServiceProvidersPage,
    startCsvExportFiltredServiceProviders
  } = useServiceProviderStore();

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

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

  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 isValidFilterValue = (value: any): boolean => {
    return value !== null && value !== undefined && value !== '';
  };

  useEffect(() => {
    const baseParams: ServiceProviderPageFilterParams = {
      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 | null> = {};
    Object.entries(tableManager.filters).forEach(([key, { value }]) => {
      if (key === 'id' && isValidFilterValue(value)) {
        filterParams[key] = Number(value);
      } else if (isValidFilterValue(value)) {
        filterParams[key] = value;
      }
    });

    if (isValidFilterValue(filterParams.keyword)) {
      filterParams.id = null;
      filterParams.name = null;
    } else if (isValidFilterValue(filterParams.id) || isValidFilterValue(filterParams.name)) {
      filterParams.keyword = null;
    }

    const newParams: ServiceProviderPageFilterParams = {
      ...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 getUserIdFromStorage = (): number => {
    const userId = localStorage.getItem('userId');
    if (!userId) {
      throw new Error('User ID not found in storage');
    }
    const parsedId = parseInt(userId);
    if (isNaN(parsedId)) {
      throw new Error('Invalid user ID in storage');
    }
    return parsedId;
  };

  const userId = getUserIdFromStorage();

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


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