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 [filteredTeams, setFilteredTeams] = useState<TeamList[]>([]);
  const { teams, totalElements, totalPages, loading, error, getAllTeams, exportTeams } = useTeamStore();

  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 === 'teamLeaderName') {
        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]);

  useEffect(() => {
    if (!tableManager.filters || Object.keys(tableManager.filters).length === 0) {
      setFilteredTeams(teams || []);
    } else {
      const filtered = teams?.filter(team => {
        return Object.entries(tableManager.filters).every(([key, filterValue]) => {
          if (!filterValue.value) return true;
          
          let teamValue;
          switch (key) {
            case 'teamLeaderName':
              teamValue = team.teamLeaderName|| '';
              break;
            case 'departmentName':
              teamValue = team.departmentName || '';
              break;
            case 'creationDate':
              if (!filterValue.value) return true;
              const filterDate = new Date(filterValue.value);
              const teamDate = new Date(team.creationDate);
              return teamDate.toISOString().split('T')[0] === filterDate.toISOString().split('T')[0];
            default:
              teamValue = team[key as keyof TeamList] || '';
          }
          
          return String(teamValue).toLowerCase().includes(filterValue.value.toLowerCase());
        });
      }) || [];
      setFilteredTeams(filtered);
    }
  }, [teams, tableManager.filters]);

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

  const refreshData = () => {
    getAllTeams(params);
  };

  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 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
      });
    }
  };

  const handleFilterChange = (key: string, value: string, condition: string) => {
    if (!value) {
      const newParams = { ...params };
      delete newParams[key as keyof TeamPageFilterParams];
      setParams(newParams);
      getAllTeams(newParams);
    }
    
    tableManager.handleFilterChange(key, value, condition);
  };

  const handleResetFilters = async () => {
    tableManager.handleResetFilters();
    const defaultParams: TeamPageFilterParams = {
      page: 0,
      size: 20,
      sortBy: 'id',
      sortDirection: 'desc'
    };
    setParams(defaultParams);
    await getAllTeams(defaultParams);
  };

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