'use client';

import React, { useEffect, useMemo, useRef } from 'react';
import { Box, Stack } from '@mui/material';
import { HEADER } from '@/layouts/config-layout';
import TableControlBar from '@/shared/components/table/table-control-bar';
import { useEquipeTabs } from '../hooks/use-equipe-tabs';
import { useEquipeTable } from '../hooks/use-equipe-table';
import EquipeTabs from '@/shared/components/tabs/tabs-custom';
import { IEquipe, TeamList, TeamStatus } from '@/shared/types/equipe';
import EquipeTable from '../components/equipe-table';
import { TableType } from '@/shared/types/common';
import { useSearchParams } from 'next/navigation';
import EquipeForm from './equipe-new-view';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';

export default function EquipeListView() {
  const searchParams = useSearchParams();
  const equipeId = searchParams.get('id');
  
  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    handleCopy,
    setTabHasUnsavedChanges,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent
  } = useEquipeTabs();

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    loading,
    error,
    totalTeams,
    page,
    rowsPerPage,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleStatusChange,
    onPageChange,
    onRowsPerPageChange,
    sortBy,
    sortDirection,
    handleSave,
    handleStartExportTeams,
    refreshData
  } = useEquipeTable();

  const isFirstRender = useRef(true);
  
  useEffect(() => {
    if (equipeId && isFirstRender.current) {
      const equipe = filteredData.find(e => e.id === equipeId);
      if (equipe) {
        handleView(equipe);
        isFirstRender.current = false;
      }
    }
  }, [handleView, equipeId, filteredData]);

  const activeTabData = React.useMemo(() => {
    return tabs.find(tab => tab.id === activeTab);
  }, [tabs, activeTab]);

  const handleTeamStatusChange = async (team: TeamList, newStatus: string) => {
    try {
      handleStatusChange(team, newStatus as TeamStatus, 'status');
    } catch (error) {
      console.error('Failed to update team status:', error);
    }
  };
  const exportOptions = useMemo(() => [
    {
      label: "Exporter en CSV",
      action: () => handleStartExportTeams()
    }
  ], [handleStartExportTeams]);


  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        height: '100%',
      }}
    >
      <Stack
        flexGrow={0}
        direction="row"
        alignItems="center"
        justifyContent="flex-end"
        spacing={{ xs: 0.5, sm: 1 }}
      >
        <TableControlBar
          type={TableType.Equipe}
          handleTabAdd={handleTabAdd}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={filteredData}
         useBackendExport={true}
          exportOptions={exportOptions}

        />
      </Stack>

      <EquipeTabs
        type={TableType.Equipe}
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      />

      {activeTab === 'list' ? (
        <EquipeTable
          filteredData={filteredData}
          table={table}
          tableHead={tableHead}
          notFound={notFound}
          loading={loading}
          filters={filters}
          onFilterChange={handleFilterChange}
          handleEdit={handleEdit}
          handleCopy={handleCopy}
          handleView={handleView}
          onStatusChange={handleTeamStatusChange}
          totalTeams={totalTeams}
          page={page ?? 0}
          rowsPerPage={rowsPerPage ?? 20}
          onPageChange={onPageChange}
          onRowsPerPageChange={onRowsPerPageChange}
          sortBy={sortBy}
          sortDirection={sortDirection}
          refreshData={refreshData}
        />
      ) : (
        <EquipeForm
          key={activeTab}
          equipe={activeTabData?.content as IEquipe}
          mode={activeTabData?.mode || 'view'}
          onSave={handleSave}
          onClose={(force) => handleCancel(activeTab, force)}
          onEdit={handleEdit}
          updateTabContent={updateTabContent}
          tabId={activeTab}
          refreshData={refreshData}
          setHasUnsavedChanges={(value: boolean) => setTabHasUnsavedChanges(activeTab, value)}
       

        tableHead={tableHead}
        />
      )}
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  );
}