import { useState, useEffect } from 'react';
import { TeamPageFilterParams, TeamList, TeamStatus } from '@/shared/types/equipe';
import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { TableColumn } from '@/shared/types/common';
import { useTeamStore } from '@/shared/api/stores/teamStore';
import React from 'react';
import { enqueueSnackbar } from 'notistack';

export const DEFAULT_TABLE_HEAD: TableColumn[] = [
  { id: 'id', label: 'N° Équipe', type: 'text' },
  { id: 'teamCode', label: 'Code équipe', type: 'text' },
  { id: 'name', label: 'Nom', type: 'text' },
  { id: 'teamLeaderFullName', label: 'Chef d\'équipe', type: 'text' },
  { id: 'departmentName', label: 'Département', type: 'text' },
  { id: 'creationDate', label: 'Date de création', type: 'date' },
  { id: 'status', label: 'Statut', type: 'status' },
  { id: '', label: 'Action' },
];

const teamConfig: TableConfig<TeamList> = {
  initialData: [],
  defaultTableHead: DEFAULT_TABLE_HEAD,
};

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

  const { teams, totalElements, totalPages, loading, error, getAllTeams,exportTeams } = useTeamStore();

  useEffect(() => {
    getAllTeams(params);
  }, [params]);
  const refreshData = () => {
    getAllTeams(params);
  };

  const tableManager = useTableManager<TeamList>({
    ...teamConfig,
    initialData: teams || [],
  });

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

  useEffect(() => {
    const baseParams: TeamPageFilterParams = {
      ...params,
      sortBy: tableManager.table.orderBy,
      sortDirection: tableManager.table.order.toLowerCase() as 'asc' | 'desc',
    };

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

    Object.entries(tableManager.filters).forEach(([key, { value }]) => {
      if (!value) return;
      if (key === 'teamLeaderFullName') {
        filterParams['teamLeaderName'] = value; 
      }
      else if (key === 'id') {
        filterParams[key] = Number(value);
      } else if (key === 'creationDate') {
        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}`;
      } else {
        filterParams[key] = value;
      }
    });

    setParams({
      ...baseParams,
      ...filterParams as Partial<TeamPageFilterParams>
    });
  }, [tableManager.filters, tableManager.table.orderBy, tableManager.table.order]);

  const handlePageChange = (event: React.MouseEvent<HTMLButtonElement> | null, newPage: number) => {
    setParams(prev => ({
      ...prev,
      page: newPage
    }));
  };
  const handleResetFilters = async () => {
    // Réinitialiser les filtres du tableau
    tableManager.handleResetFilters();
    
    // Réinitialiser les paramètres à leurs valeurs par défaut
    const defaultParams: TeamPageFilterParams = {
      page: 0,
      size: 20,
      sortBy: 'id',
      sortDirection: 'desc'
    };
    
    setParams(defaultParams);
    
   
    await getAllTeams(defaultParams);
  };
  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 handleStatusChange = (team: TeamList, newStatus: TeamStatus, field: keyof TeamList) => {
    
  };
  const handleStartExportTeams = async () => {
    try {
      const exportParams = { ...params };
      delete exportParams.page;
      delete exportParams.size;
      delete exportParams.sortBy;
      delete exportParams.sortDirection;
      
      const result = await exportTeams(exportParams);
      
      if (result) {
        enqueueSnackbar('Export réussi', { 
          variant: 'success',
          autoHideDuration: 3000
        });
      }
    } catch (error: any) {
      enqueueSnackbar(error.message || 'Erreur lors de l\'export', { 
        variant: 'error',
        autoHideDuration: 3000
      });
    }
  };

  return {
    ...tableManager,
    loading,
    error,
    totalTeams: totalElements || 0,
    page: params.page,
    rowsPerPage: params.size,
    sortBy: params.sortBy || 'id',
    sortDirection: params.sortDirection || 'desc',
    filteredData: teams || [],
    onPageChange: handlePageChange,
    onRowsPerPageChange: handleRowsPerPageChange,
    handleStatusChange,
    handleStartExportTeams,
    handleResetFilters,
    dataToExport: teams || [], 
    refreshData,
  };
}