import React from 'react';
import Checkbox from '@mui/material/Checkbox';
import TableCell from '@mui/material/TableCell';
import { TEAM_STATUS, TeamList, TeamStatus } from '@/shared/types/equipe';
import TableActionColumn from '@/shared/components/table/table-action-column';
import { EquipeStyledRow, StatusChip } from '../../styles';
import { TableColumn } from '@/shared/types/common';
import { formatDate } from '@/utils/format-time';
import StatusMenu from '@/shared/components/table/StatusMenu';
import { useTeamStore } from '@/shared/api/stores/teamStore';
import { enqueueSnackbar } from 'notistack';

type Props = {
  handleEditEquipe: (equipe: TeamList) => void;
  handleDetailsEquipe: (equipe: TeamList) => void;
  handleCopyEquipe: (equipe: TeamList) => void;
  selected: boolean;
  row: TeamList;
  onSelectRow: VoidFunction;
  columns: TableColumn[];
  onStatusChange: (row: TeamList, newStatus: TeamStatus, field: keyof TeamList) => void;
  refreshData: () => void;
};

const TOOLTIP_TITLES = {
  edit: 'Modifier équipe',
  duplicate: 'Copier équipe',
  active: 'Équipe active',
  inactive: 'Équipe inactive',
};

export default function EquipeTableRow({
  row,
  handleEditEquipe,
  handleDetailsEquipe,
  handleCopyEquipe,
  selected,
  onSelectRow,
  columns,
  onStatusChange,
  refreshData
}: Props) {
 const { toggleTeamStatus } = useTeamStore();

 const handleToggleActivation = async (isActive: boolean) => {
  try {
    await toggleTeamStatus(row.id);
    refreshData();
  } catch (error) {
    console.error('Erreur lors du changement de statut:', error);
  }
};

  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case 'creationDate':
        return formatDate(value);
        case 'status':
          return (
            <StatusMenu
              value={value}
              options={TEAM_STATUS}
              onChange={async (newStatus) => {
                try {
                  await toggleTeamStatus(row.id);
                  onStatusChange(row, newStatus as TeamStatus, 'status');
                  refreshData();
                  enqueueSnackbar('Statut modifié avec succès', { variant: 'success' });
                } catch (error: any) {
                  enqueueSnackbar(error.message || 'Erreur lors du changement de statut', {
                    variant: 'error'
                  });
                }
              }}
              chipComponent={StatusChip}
              sx={{
                width: '120px',
                '& .MuiSelect-select': {
                  py: 0,
                },
              }}
            />
          );
      default:
        return value;
    }
  };

  return (
    <EquipeStyledRow hover selected={selected} style={{ cursor: 'pointer' }}>

      {columns
        .filter((column) => column.id !== 'isActive')
        .map((column: any) => (
          <TableCell
            onDoubleClick={() => handleDetailsEquipe(row)}
            key={column.id}
            align={column.align}
            sx={{ whiteSpace: 'nowrap', py: column.id === 'status' ? 0 : 'inherit' }}
          >
            {renderCellContent(column.id, row[column.id as keyof TeamList])}
          </TableCell>
        ))}

      <TableCell align="right" sx={{ px: 1, whiteSpace: 'nowrap' }}>
        <TableActionColumn
          handleEdit={() => handleEditEquipe(row)}
          onDuplicate={() => handleCopyEquipe(row)}
          onToggle={(checked) => handleToggleActivation(checked)}
          isActive={row.status === TeamStatus.ACTIVE}
          tooltipTitles={TOOLTIP_TITLES}
        />
      </TableCell>
    </EquipeStyledRow>
  );
}