import React, { useState, useMemo } from 'react';
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  Typography,
  Box,
  IconButton,
  Tooltip,
} from '@mui/material';
import { CustomTableSortLabel } from '@/shared/components/table/table-head-custom';
import SvgColor from '@/shared/components/svg-color';
import { EquipeAgentsStyledRow } from '../../styles';
import { faTrash } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { useTeamStore } from '@/shared/api/stores/teamStore';
import { IAgent } from '@/shared/types/client';

interface EquipeAgentsTableProps {
  agentIds: string[];
  onRemoveAgent?: (agentId: string) => void;
  isReadOnly?: boolean;
}

export default function EquipeAgentsTable({
  agentIds = [],
  onRemoveAgent,
  isReadOnly = true,
}: EquipeAgentsTableProps) {
  const [order, setOrder] = useState<'asc' | 'desc'>('asc');
  const [orderBy, setOrderBy] = useState<string>('id');
  const { teamById, allCollaborators } = useTeamStore();

  const HEAD_CELLS = useMemo(() => {
    const baseColumns = [
      { id: 'number', label: 'Numéro', align: 'center' },
      { id: 'name', label: 'Nom', align: 'center' },
      { id: 'role', label: 'Rôle', align: 'center' },
      { id: 'email', label: 'Email', align: 'center' },
      { id: 'phone', label: 'Téléphone', align: 'center' },
    ];

    return isReadOnly
      ? baseColumns
      : [...baseColumns, { id: 'actions', label: 'Actions', align: 'center' }];
  }, [isReadOnly]);
const teamAgents = useMemo((): IAgent[] => {
    if (!agentIds || agentIds.length === 0) return [];

    const allAgents = teamById?.collaborators ?? allCollaborators;

    return allAgents.filter(
      (agent): agent is IAgent =>
        agentIds.includes(String(agent.id)) &&
        'firstName' in agent &&
        'lastName' in agent &&
        'roles' in agent
    );
  }, [agentIds, teamById, allCollaborators]);

  const handleSort = (property: string) => {
    setOrder((prev) => (orderBy === property && prev === 'asc' ? 'desc' : 'asc'));
    setOrderBy(property);
  };

  const sortedData: IAgent[] = useMemo(() => {
    return [...teamAgents].sort((a, b) => {
      if (orderBy) {
        let aValue: any;
        let bValue: any;

        if (orderBy === 'name') {
          aValue = `${a.firstName} ${a.lastName}` || '';
          bValue = `${b.firstName} ${b.lastName}` || '';
        } else if (orderBy === 'role') {
          aValue = a.roles?.[0]?.name || 'N/A';
          bValue = b.roles?.[0]?.name || 'N/A';
        } else if (orderBy === 'phone') {
          aValue = a.phoneNumber || 'N/A';
          bValue = b.phoneNumber || 'N/A';
        } else {
          aValue = a[orderBy as keyof IAgent] || '';
          bValue = b[orderBy as keyof IAgent] || '';
        }

        if (typeof aValue === 'string' && typeof bValue === 'string') {
          return aValue.localeCompare(bValue) * (order === 'asc' ? 1 : -1);
        } else {
          return (aValue < bValue ? -1 : 1) * (order === 'asc' ? 1 : -1);
        }
      }
      return 0;
    });
  }, [teamAgents, order, orderBy]);

  const renderAgentName = (agent: IAgent) => (
    <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <SvgColor
        src="/assets/icons/menu/ic_user.svg"
        sx={{ width: 15, color: 'primary.main', mr: 1 }}
      />
      {`${agent.firstName} ${agent.lastName}`}
    </Box>
  );

  const handleRemoveAgent = (agentId: string) => {
    if (onRemoveAgent) {
      onRemoveAgent(agentId);
    }
  };

  return (
    <Box sx={{ width: '100%', mb: '20px' }}>
      <Typography
        variant="h5"
        sx={{
          my: 2,
          color: 'primary.main',
          fontWeight: (theme) => theme.typography.fontWeightBold,
        }}
      >
        Membres de l&apos;équipe
      </Typography>
      <TableContainer>
        <Table sx={{ borderRadius: '12px' }}>
          <TableHead sx={{ backgroundColor: 'white' }}>
            <EquipeAgentsStyledRow>
              {HEAD_CELLS.map((headCell) => (
                <TableCell
                  sx={{ px: { xs: 6, xl: 3 }, py: 3 }}
                  key={headCell.id}
                  align="center"
                  sortDirection={orderBy === headCell.id ? order : false}
                >
                  <CustomTableSortLabel
                    active={orderBy === headCell.id}
                    direction={orderBy === headCell.id ? order : 'asc'}
                    orderBy={orderBy}
                    order={order}
                    onSort={() => handleSort(headCell.id)}
                  >
                    {headCell.label}
                  </CustomTableSortLabel>
                </TableCell>
              ))}
            </EquipeAgentsStyledRow>
          </TableHead>
          <TableBody>
            {sortedData.length > 0 ? (
              sortedData.map((agent) => (
                <EquipeAgentsStyledRow key={agent.id}>
                  <TableCell align="center" sx={{ py: 2, px: { xs: 1, xl: 2 } }}>
                    {agent.id}
                  </TableCell>
                  <TableCell align="center" sx={{ py: 2, px: { xs: 1, xl: 2 } }}>
                    {renderAgentName(agent)}
                  </TableCell>
                  <TableCell align="center" sx={{ py: 2, px: { xs: 1, xl: 2 } }}>
                    {agent.roles?.[0]?.name || 'Collaborateur'}
                  </TableCell>
                  <TableCell align="center" sx={{ py: 2, px: { xs: 1, xl: 2 } }}>
                    {agent.email}
                  </TableCell>
                  <TableCell align="center" sx={{ py: 2, px: { xs: 1, xl: 2 } }}>
                    {agent.phoneNumber || 'N/A'}
                  </TableCell>
                  {!isReadOnly && (
                    <TableCell align="center" sx={{ py: 2, px: { xs: 1, xl: 2 } }}>
                      {onRemoveAgent && (
                        <Tooltip
                          title="Supprimer de l'équipe"
                          arrow
                          componentsProps={{
                            tooltip: {
                              sx: {
                                bgcolor: 'primary.main',
                                color: 'white',
                                '& .MuiTooltip-arrow': {
                                  color: 'primary.main',
                                },
                              },
                            },
                          }}
                        >
                          <IconButton
                            sx={{ '&:hover': { color: 'primary.main' } }}
                            onClick={() => handleRemoveAgent(String(agent.id))}
                            size="medium"
                          >
                            <FontAwesomeIcon icon={faTrash} size="sm" style={{ fontSize: '1rem' }} />
                          </IconButton>
                        </Tooltip>
                      )}
                    </TableCell>
                  )}
                </EquipeAgentsStyledRow>
              ))
            ) : (
              <EquipeAgentsStyledRow>
                <TableCell colSpan={HEAD_CELLS.length} align="center" sx={{ py: 3 }}>
                  Aucun membre dans cette équipe
                </TableCell>
              </EquipeAgentsStyledRow>
            )}
          </TableBody>
        </Table>
      </TableContainer>
    </Box>
  );
}
