import { Box, Typography, Fade } from "@mui/material";
import { Navigation as CursorIcon } from "@mui/icons-material";
import { useCollaboration, useRemoteCursorsForView } from "../../contexts/CollaborationContext";

interface RemoteCursorsProps {
  /** Current view ID to filter cursors */
  viewId?: string | null;
  /** Zoom level for coordinate transformation */
  zoom?: number;
  /** Container offset X (for absolute positioning) */
  offsetX?: number;
  /** Container offset Y (for absolute positioning) */
  offsetY?: number;
  /** Whether cursors are in mm coordinates (needs conversion to px) */
  coordinatesInMm?: boolean;
  /** MM to PX ratio if coordinatesInMm is true */
  mmToPxRatio?: number;
}

/**
 * Overlay component that displays remote collaborator cursors
 * Should be placed in a relative positioned container
 */
export default function RemoteCursors({
  viewId = null,
  zoom = 1,
  offsetX = 0,
  offsetY = 0,
  coordinatesInMm = false,
  mmToPxRatio = 3.7795275591,
}: RemoteCursorsProps) {
  const cursors = useRemoteCursorsForView(viewId);

  if (cursors.length === 0) {
    return null;
  }

  return (
    <Box
      sx={{
        position: "absolute",
        top: 0,
        left: 0,
        width: "100%",
        height: "100%",
        pointerEvents: "none",
        overflow: "hidden",
        zIndex: 1000,
      }}
    >
      {cursors.map((cursor) => {
        // Convert coordinates if needed
        let x = cursor.x;
        let y = cursor.y;

        if (coordinatesInMm) {
          x = cursor.x * mmToPxRatio;
          y = cursor.y * mmToPxRatio;
        }

        // Apply zoom and offset
        x = x * zoom + offsetX;
        y = y * zoom + offsetY;

        return (
          <Fade key={cursor.connectionId} in={true} timeout={200}>
            <Box
              sx={{
                position: "absolute",
                left: x,
                top: y,
                transform: "translate(-2px, -2px)",
                transition: "left 0.05s linear, top 0.05s linear",
              }}
            >
              {/* Cursor icon */}
              <CursorIcon
                sx={{
                  fontSize: 20,
                  color: cursor.color,
                  filter: "drop-shadow(0 1px 2px rgba(0,0,0,0.3))",
                  transform: "rotate(-45deg)",
                }}
              />

              {/* User name label */}
              <Box
                sx={{
                  position: "absolute",
                  left: 16,
                  top: 12,
                  bgcolor: cursor.color,
                  color: "white",
                  px: 0.75,
                  py: 0.25,
                  borderRadius: 0.5,
                  fontSize: "0.65rem",
                  fontWeight: 500,
                  whiteSpace: "nowrap",
                  boxShadow: "0 1px 3px rgba(0,0,0,0.2)",
                  maxWidth: 120,
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                }}
              >
                {cursor.userName}
              </Box>
            </Box>
          </Fade>
        );
      })}
    </Box>
  );
}

/**
 * Component to highlight items selected by remote users
 */
interface RemoteSelectionHighlightProps {
  itemId: string;
  children: React.ReactNode;
}

export function RemoteSelectionHighlight({ itemId, children }: RemoteSelectionHighlightProps) {
  const { remoteSelections, collaborators } = useCollaboration();

  // Find if any collaborator has this item selected
  let selectedBy: { userName: string; color: string } | null = null;

  for (const [connectionId, selectedId] of remoteSelections.entries()) {
    if (selectedId === itemId) {
      const collaborator = collaborators.find((c) => c.connectionId === connectionId);
      if (collaborator) {
        selectedBy = { userName: collaborator.userName, color: collaborator.color };
        break;
      }
    }
  }

  if (!selectedBy) {
    return <>{children}</>;
  }

  return (
    <Box
      sx={{
        position: "relative",
        outline: `2px solid ${selectedBy.color}`,
        outlineOffset: 2,
        borderRadius: 1,
      }}
    >
      {children}

      {/* Selection indicator */}
      <Typography
        variant="caption"
        sx={{
          position: "absolute",
          top: -20,
          left: 0,
          bgcolor: selectedBy.color,
          color: "white",
          px: 0.75,
          py: 0.25,
          borderRadius: 0.5,
          fontSize: "0.6rem",
          fontWeight: 500,
          whiteSpace: "nowrap",
          zIndex: 1,
        }}
      >
        {selectedBy.userName}
      </Typography>
    </Box>
  );
}
