import { memo, useMemo } from "react";
import {
  Menu,
  MenuItem,
  ListItemIcon,
  ListItemText,
  Divider,
  Typography,
  Box,
} from "@mui/material";
import {
  ContentCopy as CopyIcon,
  ContentCut as CutIcon,
  ContentPaste as PasteIcon,
  Delete as DeleteIcon,
  FileCopy as DuplicateIcon,
  Lock as LockIcon,
  LockOpen as UnlockIcon,
  FlipToFront as BringToFrontIcon,
  FlipToBack as SendToBackIcon,
  KeyboardArrowUp as BringForwardIcon,
  KeyboardArrowDown as SendBackwardIcon,
  VerticalAlignTop as AlignTopIcon,
  VerticalAlignCenter as AlignMiddleIcon,
  VerticalAlignBottom as AlignBottomIcon,
  AlignHorizontalLeft as AlignLeftIcon,
  AlignHorizontalCenter as AlignCenterIcon,
  AlignHorizontalRight as AlignRightIcon,
  GroupWork as GroupIcon,
  CallSplit as UngroupIcon,
  Rotate90DegreesCw as RotateRightIcon,
  Rotate90DegreesCcw as RotateLeftIcon,
  Flip as FlipHorizontalIcon,
  SwapVert as FlipVerticalIcon,
  CenterFocusStrong as CenterIcon,
  AspectRatio as FitToPageIcon,
  SelectAll as SelectAllIcon,
  Deselect as DeselectIcon,
  Visibility as ShowIcon,
  VisibilityOff as HideIcon,
  TextFields as EditTextIcon,
  Image as ReplaceImageIcon,
} from "@mui/icons-material";
import type { AprtElement } from "../../types/report";

export interface ContextMenuPosition {
  x: number;
  y: number;
}

export interface ContextMenuProps {
  open: boolean;
  position: ContextMenuPosition | null;
  selectedElement: AprtElement | null;
  selectedElements: AprtElement[];
  hasClipboard: boolean;
  onClose: () => void;
  // Element actions
  onCopy: () => void;
  onCut: () => void;
  onPaste: () => void;
  onDuplicate: () => void;
  onDelete: () => void;
  onLock: () => void;
  onUnlock: () => void;
  // Layer actions
  onBringToFront: () => void;
  onSendToBack: () => void;
  onBringForward: () => void;
  onSendBackward: () => void;
  // Alignment actions
  onAlignLeft: () => void;
  onAlignCenter: () => void;
  onAlignRight: () => void;
  onAlignTop: () => void;
  onAlignMiddle: () => void;
  onAlignBottom: () => void;
  onCenterOnPage: () => void;
  // Transform actions
  onRotateLeft: () => void;
  onRotateRight: () => void;
  onFlipHorizontal: () => void;
  onFlipVertical: () => void;
  // Group actions
  onGroup: () => void;
  onUngroup: () => void;
  // Selection actions
  onSelectAll: () => void;
  onDeselectAll: () => void;
  // Visibility
  onToggleVisibility: () => void;
  // Type-specific actions
  onEditText?: () => void;
  onReplaceImage?: () => void;
  onFitToContent?: () => void;
}

interface MenuSection {
  id: string;
  items: MenuItemConfig[];
}

interface MenuItemConfig {
  id: string;
  label: string;
  icon: React.ReactNode;
  shortcut?: string;
  action: () => void;
  disabled?: boolean;
  show?: boolean;
  danger?: boolean;
  submenu?: MenuItemConfig[];
}

const ContextMenu = memo(function ContextMenu({
  open,
  position,
  selectedElement,
  selectedElements,
  hasClipboard,
  onClose,
  onCopy,
  onCut,
  onPaste,
  onDuplicate,
  onDelete,
  onLock,
  onUnlock,
  onBringToFront,
  onSendToBack,
  onBringForward,
  onSendBackward,
  onAlignLeft,
  onAlignCenter,
  onAlignRight,
  onAlignTop,
  onAlignMiddle,
  onAlignBottom,
  onCenterOnPage,
  onRotateLeft,
  onRotateRight,
  onFlipHorizontal,
  onFlipVertical,
  onGroup,
  onUngroup,
  onSelectAll,
  onDeselectAll,
  onToggleVisibility,
  onEditText,
  onReplaceImage,
  onFitToContent,
}: ContextMenuProps) {
  const hasSelection = selectedElement !== null;
  const hasMultipleSelection = selectedElements.length > 1;
  const isLocked = selectedElement?.locked ?? false;
  const isVisible = selectedElement?.visible ?? true;
  const isText = selectedElement?.type === "text";
  const isImage = selectedElement?.type === "image";
  const isGroup = selectedElement?.type === "table"; // Tables are groups

  const menuSections = useMemo((): MenuSection[] => {
    const sections: MenuSection[] = [];

    // Clipboard section
    sections.push({
      id: "clipboard",
      items: [
        {
          id: "cut",
          label: "Taglia",
          icon: <CutIcon fontSize="small" />,
          shortcut: "Ctrl+X",
          action: onCut,
          disabled: !hasSelection || isLocked,
        },
        {
          id: "copy",
          label: "Copia",
          icon: <CopyIcon fontSize="small" />,
          shortcut: "Ctrl+C",
          action: onCopy,
          disabled: !hasSelection,
        },
        {
          id: "paste",
          label: "Incolla",
          icon: <PasteIcon fontSize="small" />,
          shortcut: "Ctrl+V",
          action: onPaste,
          disabled: !hasClipboard,
        },
        {
          id: "duplicate",
          label: "Duplica",
          icon: <DuplicateIcon fontSize="small" />,
          shortcut: "Ctrl+D",
          action: onDuplicate,
          disabled: !hasSelection,
        },
      ],
    });

    // Type-specific section
    if (hasSelection) {
      const typeSpecificItems: MenuItemConfig[] = [];

      if (isText && onEditText) {
        typeSpecificItems.push({
          id: "edit-text",
          label: "Modifica testo",
          icon: <EditTextIcon fontSize="small" />,
          shortcut: "Doppio click",
          action: onEditText,
          disabled: isLocked,
        });
      }

      if (isImage && onReplaceImage) {
        typeSpecificItems.push({
          id: "replace-image",
          label: "Sostituisci immagine",
          icon: <ReplaceImageIcon fontSize="small" />,
          action: onReplaceImage,
          disabled: isLocked,
        });
      }

      if (onFitToContent) {
        typeSpecificItems.push({
          id: "fit-to-content",
          label: "Adatta al contenuto",
          icon: <FitToPageIcon fontSize="small" />,
          action: onFitToContent,
          disabled: isLocked,
        });
      }

      if (typeSpecificItems.length > 0) {
        sections.push({
          id: "type-specific",
          items: typeSpecificItems,
        });
      }
    }

    // Layer section
    if (hasSelection) {
      sections.push({
        id: "layer",
        items: [
          {
            id: "bring-to-front",
            label: "Porta in primo piano",
            icon: <BringToFrontIcon fontSize="small" />,
            shortcut: "Ctrl+Shift+]",
            action: onBringToFront,
            disabled: isLocked,
          },
          {
            id: "bring-forward",
            label: "Porta avanti",
            icon: <BringForwardIcon fontSize="small" />,
            shortcut: "Ctrl+]",
            action: onBringForward,
            disabled: isLocked,
          },
          {
            id: "send-backward",
            label: "Porta indietro",
            icon: <SendBackwardIcon fontSize="small" />,
            shortcut: "Ctrl+[",
            action: onSendBackward,
            disabled: isLocked,
          },
          {
            id: "send-to-back",
            label: "Porta in fondo",
            icon: <SendToBackIcon fontSize="small" />,
            shortcut: "Ctrl+Shift+[",
            action: onSendToBack,
            disabled: isLocked,
          },
        ],
      });
    }

    // Alignment section
    if (hasSelection) {
      sections.push({
        id: "align",
        items: [
          {
            id: "align-left",
            label: "Allinea a sinistra",
            icon: <AlignLeftIcon fontSize="small" />,
            action: onAlignLeft,
            disabled: isLocked,
          },
          {
            id: "align-center-h",
            label: "Allinea al centro (H)",
            icon: <AlignCenterIcon fontSize="small" />,
            action: onAlignCenter,
            disabled: isLocked,
          },
          {
            id: "align-right",
            label: "Allinea a destra",
            icon: <AlignRightIcon fontSize="small" />,
            action: onAlignRight,
            disabled: isLocked,
          },
          {
            id: "align-top",
            label: "Allinea in alto",
            icon: <AlignTopIcon fontSize="small" />,
            action: onAlignTop,
            disabled: isLocked,
          },
          {
            id: "align-middle",
            label: "Allinea al centro (V)",
            icon: <AlignMiddleIcon fontSize="small" />,
            action: onAlignMiddle,
            disabled: isLocked,
          },
          {
            id: "align-bottom",
            label: "Allinea in basso",
            icon: <AlignBottomIcon fontSize="small" />,
            action: onAlignBottom,
            disabled: isLocked,
          },
          {
            id: "center-on-page",
            label: "Centra nella pagina",
            icon: <CenterIcon fontSize="small" />,
            action: onCenterOnPage,
            disabled: isLocked,
          },
        ],
      });
    }

    // Transform section
    if (hasSelection) {
      sections.push({
        id: "transform",
        items: [
          {
            id: "rotate-left",
            label: "Ruota 90° sinistra",
            icon: <RotateLeftIcon fontSize="small" />,
            action: onRotateLeft,
            disabled: isLocked,
          },
          {
            id: "rotate-right",
            label: "Ruota 90° destra",
            icon: <RotateRightIcon fontSize="small" />,
            action: onRotateRight,
            disabled: isLocked,
          },
          {
            id: "flip-horizontal",
            label: "Rifletti orizzontalmente",
            icon: <FlipHorizontalIcon fontSize="small" />,
            shortcut: "H",
            action: onFlipHorizontal,
            disabled: isLocked,
          },
          {
            id: "flip-vertical",
            label: "Rifletti verticalmente",
            icon: <FlipVerticalIcon fontSize="small" />,
            shortcut: "V",
            action: onFlipVertical,
            disabled: isLocked,
          },
        ],
      });
    }

    // Group section
    if (hasMultipleSelection || isGroup) {
      sections.push({
        id: "group",
        items: [
          {
            id: "group",
            label: "Raggruppa",
            icon: <GroupIcon fontSize="small" />,
            shortcut: "Ctrl+G",
            action: onGroup,
            show: hasMultipleSelection,
            disabled: isLocked,
          },
          {
            id: "ungroup",
            label: "Separa",
            icon: <UngroupIcon fontSize="small" />,
            shortcut: "Ctrl+Shift+G",
            action: onUngroup,
            show: isGroup,
            disabled: isLocked,
          },
        ].filter((item) => item.show !== false),
      });
    }

    // Lock & visibility section
    if (hasSelection) {
      sections.push({
        id: "lock-visibility",
        items: [
          {
            id: "lock",
            label: isLocked ? "Sblocca" : "Blocca",
            icon: isLocked ? (
              <UnlockIcon fontSize="small" />
            ) : (
              <LockIcon fontSize="small" />
            ),
            shortcut: "Ctrl+L",
            action: isLocked ? onUnlock : onLock,
          },
          {
            id: "visibility",
            label: isVisible ? "Nascondi" : "Mostra",
            icon: isVisible ? (
              <HideIcon fontSize="small" />
            ) : (
              <ShowIcon fontSize="small" />
            ),
            action: onToggleVisibility,
          },
        ],
      });
    }

    // Selection section
    sections.push({
      id: "selection",
      items: [
        {
          id: "select-all",
          label: "Seleziona tutto",
          icon: <SelectAllIcon fontSize="small" />,
          shortcut: "Ctrl+A",
          action: onSelectAll,
        },
        {
          id: "deselect",
          label: "Deseleziona",
          icon: <DeselectIcon fontSize="small" />,
          shortcut: "Esc",
          action: onDeselectAll,
          disabled: !hasSelection,
        },
      ],
    });

    // Delete section (always last)
    if (hasSelection) {
      sections.push({
        id: "delete",
        items: [
          {
            id: "delete",
            label: "Elimina",
            icon: <DeleteIcon fontSize="small" />,
            shortcut: "Canc",
            action: onDelete,
            disabled: isLocked,
            danger: true,
          },
        ],
      });
    }

    return sections;
  }, [
    hasSelection,
    hasMultipleSelection,
    isLocked,
    isVisible,
    isText,
    isImage,
    isGroup,
    hasClipboard,
    onCut,
    onCopy,
    onPaste,
    onDuplicate,
    onDelete,
    onLock,
    onUnlock,
    onBringToFront,
    onSendToBack,
    onBringForward,
    onSendBackward,
    onAlignLeft,
    onAlignCenter,
    onAlignRight,
    onAlignTop,
    onAlignMiddle,
    onAlignBottom,
    onCenterOnPage,
    onRotateLeft,
    onRotateRight,
    onFlipHorizontal,
    onFlipVertical,
    onGroup,
    onUngroup,
    onSelectAll,
    onDeselectAll,
    onToggleVisibility,
    onEditText,
    onReplaceImage,
    onFitToContent,
  ]);

  if (!position) return null;

  return (
    <Menu
      open={open}
      onClose={onClose}
      anchorReference="anchorPosition"
      anchorPosition={{ top: position.y, left: position.x }}
      slotProps={{
        paper: {
          elevation: 8,
          sx: {
            minWidth: 240,
            maxWidth: 320,
            borderRadius: 2,
            overflow: "visible",
            "& .MuiMenuItem-root": {
              fontSize: "0.875rem",
              py: 0.75,
              px: 2,
              borderRadius: 1,
              mx: 0.5,
              "&:hover": {
                bgcolor: "action.hover",
              },
              "&.Mui-disabled": {
                opacity: 0.5,
              },
            },
            "& .MuiListItemIcon-root": {
              minWidth: 32,
            },
          },
        },
      }}
    >
      {/* Header when element is selected */}
      {selectedElement && (
        <Box sx={{ px: 2, py: 1, borderBottom: 1, borderColor: "divider" }}>
          <Typography
            variant="caption"
            color="text.secondary"
            sx={{ textTransform: "uppercase", letterSpacing: 0.5 }}
          >
            {selectedElement.type === "text" && "Testo"}
            {selectedElement.type === "image" && "Immagine"}
            {selectedElement.type === "shape" && "Forma"}
            {selectedElement.type === "line" && "Linea"}
            {selectedElement.type === "table" && "Tabella"}
            {hasMultipleSelection && ` (+${selectedElements.length - 1})`}
          </Typography>
          {selectedElement.name && (
            <Typography variant="body2" noWrap>
              {selectedElement.name}
            </Typography>
          )}
        </Box>
      )}

      {menuSections.map((section, sectionIndex) => (
        <Box key={section.id}>
          {sectionIndex > 0 && <Divider sx={{ my: 0.5 }} />}
          {section.items
            .filter((item) => item.show !== false)
            .map((item) => (
              <MenuItem
                key={item.id}
                onClick={() => {
                  item.action();
                  onClose();
                }}
                disabled={item.disabled}
                sx={{
                  color: item.danger ? "error.main" : "inherit",
                  "&:hover": {
                    bgcolor: item.danger ? "error.light" : "action.hover",
                  },
                }}
              >
                <ListItemIcon
                  sx={{ color: item.danger ? "error.main" : "inherit" }}
                >
                  {item.icon}
                </ListItemIcon>
                <ListItemText primary={item.label} />
                {item.shortcut && (
                  <Typography
                    variant="caption"
                    color="text.secondary"
                    sx={{ ml: 2, opacity: 0.7 }}
                  >
                    {item.shortcut}
                  </Typography>
                )}
              </MenuItem>
            ))}
        </Box>
      ))}
    </Menu>
  );
});

export default ContextMenu;
