import { useState } from "react";
import {
  Avatar,
  AvatarGroup,
  Badge,
  Box,
  Chip,
  Collapse,
  Divider,
  IconButton,
  List,
  ListItem,
  ListItemAvatar,
  ListItemText,
  Paper,
  Popover,
  Tooltip,
  Typography,
  useTheme,
} from "@mui/material";
import {
  Circle as CircleIcon,
  ExpandLess,
  ExpandMore,
  History as HistoryIcon,
  People as PeopleIcon,
  SignalWifiOff as DisconnectedIcon,
  Wifi as ConnectedIcon,
  WifiFind as ConnectingIcon,
} from "@mui/icons-material";
import { useCollaboration } from "../../contexts/CollaborationContext";
import type { Collaborator } from "../../services/collaboration";

interface CollaborationIndicatorProps {
  /** Show only when in a room */
  showOnlyInRoom?: boolean;
  /** Show change history button */
  showHistory?: boolean;
  /** Compact mode for mobile */
  compact?: boolean;
  /** Click handler for collaborator avatar */
  onCollaboratorClick?: (collaborator: Collaborator) => void;
}

export default function CollaborationIndicator({
  showOnlyInRoom = true,
  showHistory = true,
  compact = false,
  onCollaboratorClick,
}: CollaborationIndicatorProps) {
  const theme = useTheme();
  const {
    isConnected,
    isConnecting,
    currentRoom,
    localUserName,
    localUserColor,
    collaborators,
    remoteSelections,
    changeHistory,
  } = useCollaboration();

  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
  const [historyAnchorEl, setHistoryAnchorEl] = useState<HTMLElement | null>(
    null,
  );
  const [showHistoryList, setShowHistoryList] = useState(true);

  // Don't show if not in a room and showOnlyInRoom is true
  if (showOnlyInRoom && !currentRoom) {
    return null;
  }

  const handleCollaboratorsClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const handleHistoryClick = (event: React.MouseEvent<HTMLElement>) => {
    setHistoryAnchorEl(event.currentTarget);
  };

  const handleHistoryClose = () => {
    setHistoryAnchorEl(null);
  };

  const open = Boolean(anchorEl);
  const historyOpen = Boolean(historyAnchorEl);
  const totalUsers = collaborators.length + 1;

  // Format timestamp
  const formatRelativeTime = (date: Date): string => {
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffSec = Math.floor(diffMs / 1000);
    const diffMin = Math.floor(diffSec / 60);
    const diffHour = Math.floor(diffMin / 60);

    if (diffSec < 5) return "ora";
    if (diffSec < 60) return `${diffSec}s fa`;
    if (diffMin < 60) return `${diffMin}m fa`;
    if (diffHour < 24) return `${diffHour}h fa`;
    return date.toLocaleDateString("it-IT");
  };

  // Get initials from name
  const getInitials = (name: string): string => {
    const parts = name.split(" ");
    if (parts.length >= 2) {
      return (parts[0][0] + parts[1][0]).toUpperCase();
    }
    return name.substring(0, 2).toUpperCase();
  };

  return (
    <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
      {/* Connection indicator */}
      <Tooltip
        title={
          isConnecting
            ? "Connessione in corso..."
            : isConnected
              ? currentRoom
                ? `Collaborazione attiva: ${currentRoom}`
                : "Connesso"
              : "Disconnesso"
        }
      >
        <Box
          sx={{
            display: "flex",
            alignItems: "center",
            color: isConnecting
              ? theme.palette.warning.main
              : isConnected
                ? theme.palette.success.main
                : theme.palette.error.main,
          }}
        >
          {isConnecting ? (
            <ConnectingIcon fontSize="small" />
          ) : isConnected ? (
            <ConnectedIcon fontSize="small" />
          ) : (
            <DisconnectedIcon fontSize="small" />
          )}
        </Box>
      </Tooltip>

      {/* Collaborators avatars */}
      {currentRoom && (
        <Tooltip
          title={`${totalUsers} utente${totalUsers > 1 ? "i" : ""} connesso${totalUsers > 1 ? "i" : ""}`}
        >
          <Badge
            badgeContent={totalUsers}
            color="primary"
            sx={{ cursor: "pointer" }}
            onClick={handleCollaboratorsClick}
          >
            <AvatarGroup
              max={compact ? 3 : 4}
              sx={{
                "& .MuiAvatar-root": {
                  width: compact ? 24 : 28,
                  height: compact ? 24 : 28,
                  fontSize: compact ? "0.65rem" : "0.75rem",
                  border: `2px solid ${theme.palette.background.paper}`,
                  cursor: "pointer",
                },
              }}
            >
              {/* Local user avatar */}
              <Tooltip title={`${localUserName} (tu)`}>
                <Avatar sx={{ bgcolor: localUserColor }}>
                  {getInitials(localUserName)}
                </Avatar>
              </Tooltip>

              {/* Remote collaborators */}
              {collaborators.map((collab) => (
                <Tooltip
                  key={collab.connectionId}
                  title={`${collab.userName}${remoteSelections.get(collab.connectionId) ? " - sta modificando" : ""}`}
                >
                  <Avatar
                    sx={{
                      bgcolor: collab.color,
                      boxShadow: remoteSelections.get(collab.connectionId)
                        ? `0 0 0 2px ${collab.color}`
                        : undefined,
                    }}
                  >
                    {getInitials(collab.userName)}
                  </Avatar>
                </Tooltip>
              ))}
            </AvatarGroup>
          </Badge>
        </Tooltip>
      )}

      {/* History button */}
      {showHistory && changeHistory.length > 0 && (
        <Tooltip title="Cronologia modifiche">
          <IconButton size="small" onClick={handleHistoryClick}>
            <Badge
              badgeContent={changeHistory.length}
              color="secondary"
              max={99}
            >
              <HistoryIcon fontSize="small" />
            </Badge>
          </IconButton>
        </Tooltip>
      )}

      {/* Collaborators popover */}
      <Popover
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
        transformOrigin={{ vertical: "top", horizontal: "right" }}
      >
        <Paper sx={{ minWidth: 280, maxWidth: 350, p: 2 }}>
          <Box sx={{ display: "flex", alignItems: "center", gap: 1, mb: 2 }}>
            <PeopleIcon color="primary" />
            <Typography variant="subtitle1" fontWeight="bold">
              Collaboratori ({totalUsers})
            </Typography>
          </Box>

          {currentRoom && (
            <Chip
              label={currentRoom}
              size="small"
              variant="outlined"
              sx={{ mb: 2 }}
            />
          )}

          <List dense disablePadding>
            {/* Local user */}
            <ListItem
              sx={{
                bgcolor: theme.palette.action.selected,
                borderRadius: 1,
                mb: 0.5,
              }}
            >
              <ListItemAvatar>
                <Avatar sx={{ bgcolor: localUserColor, width: 32, height: 32 }}>
                  {getInitials(localUserName)}
                </Avatar>
              </ListItemAvatar>
              <ListItemText
                primary={
                  <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                    {localUserName}
                    <Chip label="Tu" size="small" color="primary" />
                  </Box>
                }
                secondary="Connesso"
              />
            </ListItem>

            {/* Remote collaborators */}
            {collaborators.map((collab) => {
              const isEditing = remoteSelections.get(collab.connectionId);
              return (
                <ListItem
                  key={collab.connectionId}
                  sx={{
                    borderRadius: 1,
                    mb: 0.5,
                    cursor: onCollaboratorClick ? "pointer" : "default",
                    "&:hover": onCollaboratorClick
                      ? { bgcolor: theme.palette.action.hover }
                      : {},
                  }}
                  onClick={() => onCollaboratorClick?.(collab)}
                >
                  <ListItemAvatar>
                    <Badge
                      overlap="circular"
                      anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
                      badgeContent={
                        isEditing ? (
                          <CircleIcon
                            sx={{
                              color: collab.color,
                              fontSize: 12,
                              animation: "pulse 1.5s infinite",
                              "@keyframes pulse": {
                                "0%": { opacity: 1 },
                                "50%": { opacity: 0.5 },
                                "100%": { opacity: 1 },
                              },
                            }}
                          />
                        ) : null
                      }
                    >
                      <Avatar
                        sx={{ bgcolor: collab.color, width: 32, height: 32 }}
                      >
                        {getInitials(collab.userName)}
                      </Avatar>
                    </Badge>
                  </ListItemAvatar>
                  <ListItemText
                    primary={collab.userName}
                    secondary={
                      isEditing ? (
                        <Typography
                          variant="caption"
                          sx={{ color: collab.color, fontWeight: 500 }}
                        >
                          Sta modificando...
                        </Typography>
                      ) : (
                        "Online"
                      )
                    }
                  />
                </ListItem>
              );
            })}

            {collaborators.length === 0 && (
              <ListItem>
                <ListItemText
                  secondary="Nessun altro collaboratore connesso"
                  sx={{ textAlign: "center", color: "text.secondary" }}
                />
              </ListItem>
            )}
          </List>
        </Paper>
      </Popover>

      {/* History popover */}
      <Popover
        open={historyOpen}
        anchorEl={historyAnchorEl}
        onClose={handleHistoryClose}
        anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
        transformOrigin={{ vertical: "top", horizontal: "right" }}
      >
        <Paper
          sx={{
            minWidth: 320,
            maxWidth: 400,
            maxHeight: 400,
            overflow: "auto",
          }}
        >
          <Box
            sx={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              p: 2,
              pb: 1,
              position: "sticky",
              top: 0,
              bgcolor: "background.paper",
              zIndex: 1,
            }}
          >
            <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
              <HistoryIcon color="primary" />
              <Typography variant="subtitle1" fontWeight="bold">
                Modifiche Recenti
              </Typography>
            </Box>
            <IconButton
              size="small"
              onClick={() => setShowHistoryList(!showHistoryList)}
            >
              {showHistoryList ? <ExpandLess /> : <ExpandMore />}
            </IconButton>
          </Box>

          <Collapse in={showHistoryList}>
            <List dense disablePadding sx={{ px: 1, pb: 1 }}>
              {changeHistory.slice(0, 30).map((entry, index) => (
                <Box key={entry.id}>
                  <ListItem
                    sx={{
                      py: 0.5,
                      borderLeft: `3px solid ${entry.userColor}`,
                      pl: 1,
                      ml: 1,
                    }}
                  >
                    <ListItemText
                      primary={
                        <Box
                          sx={{
                            display: "flex",
                            justifyContent: "space-between",
                            alignItems: "center",
                          }}
                        >
                          <Typography variant="body2" fontWeight={500}>
                            {entry.description}
                          </Typography>
                          <Typography
                            variant="caption"
                            color="text.secondary"
                            sx={{ ml: 1, flexShrink: 0 }}
                          >
                            {formatRelativeTime(entry.timestamp)}
                          </Typography>
                        </Box>
                      }
                      secondary={
                        <Typography
                          variant="caption"
                          sx={{ color: entry.userColor }}
                        >
                          {entry.userName}
                        </Typography>
                      }
                    />
                  </ListItem>
                  {index < changeHistory.length - 1 && (
                    <Divider variant="inset" component="li" sx={{ ml: 2 }} />
                  )}
                </Box>
              ))}

              {changeHistory.length === 0 && (
                <ListItem>
                  <ListItemText
                    secondary="Nessuna modifica recente"
                    sx={{ textAlign: "center" }}
                  />
                </ListItem>
              )}

              {changeHistory.length > 30 && (
                <ListItem>
                  <ListItemText
                    secondary={`...e altre ${changeHistory.length - 30} modifiche`}
                    sx={{ textAlign: "center", fontStyle: "italic" }}
                  />
                </ListItem>
              )}
            </List>
          </Collapse>
        </Paper>
      </Popover>
    </Box>
  );
}
