import { useState } from "react";
import {
  Box,
  Typography,
  IconButton,
  Button,
  List,
  ListItem,
  ListItemButton,
  ListItemText,
  ListItemSecondaryAction,
  Menu,
  MenuItem,
  ListItemIcon,
  Divider,
  Tooltip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import {
  Add as AddIcon,
  MoreVert as MoreIcon,
  ContentCopy as DuplicateIcon,
  Delete as DeleteIcon,
  Edit as EditIcon,
  KeyboardArrowUp as MoveUpIcon,
  KeyboardArrowDown as MoveDownIcon,
} from "@mui/icons-material";
import type { AprtPage, AprtElement } from "../../types/report";

interface PageNavigatorProps {
  pages: AprtPage[];
  elements: AprtElement[];
  currentPageId: string;
  onSelectPage: (pageId: string) => void;
  onAddPage: () => void;
  onDuplicatePage: (pageId: string) => void;
  onDeletePage: (pageId: string) => void;
  onRenamePage: (pageId: string, newName: string) => void;
  onMovePage: (pageId: string, direction: "up" | "down") => void;
  /** When true, hides header and borders (used inside CollapsiblePanel) */
  embedded?: boolean;
}

export default function PageNavigator({
  pages,
  elements,
  currentPageId,
  onSelectPage,
  onAddPage,
  onDuplicatePage,
  onDeletePage,
  onRenamePage,
  onMovePage,
  embedded = false,
}: PageNavigatorProps) {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));

  const [menuAnchor, setMenuAnchor] = useState<{
    element: HTMLElement;
    pageId: string;
  } | null>(null);
  const [renameDialog, setRenameDialog] = useState<{
    open: boolean;
    pageId: string;
    currentName: string;
  }>({ open: false, pageId: "", currentName: "" });
  const [deleteConfirm, setDeleteConfirm] = useState<{
    open: boolean;
    pageId: string;
    pageName: string;
  }>({ open: false, pageId: "", pageName: "" });

  // Count elements per page
  const getElementCount = (pageId: string) => {
    return elements.filter(
      (e) => e.pageId === pageId || (!e.pageId && pageId === pages[0]?.id),
    ).length;
  };

  // Get page index
  const getPageIndex = (pageId: string) => {
    return pages.findIndex((p) => p.id === pageId);
  };

  // Handle menu open
  const handleMenuOpen = (
    event: React.MouseEvent<HTMLElement>,
    pageId: string,
  ) => {
    event.stopPropagation();
    setMenuAnchor({ element: event.currentTarget, pageId });
  };

  // Handle menu close
  const handleMenuClose = () => {
    setMenuAnchor(null);
  };

  // Handle rename
  const handleRenameClick = () => {
    const page = pages.find((p) => p.id === menuAnchor?.pageId);
    if (page) {
      setRenameDialog({
        open: true,
        pageId: page.id,
        currentName: page.name,
      });
    }
    handleMenuClose();
  };

  // Handle rename confirm
  const handleRenameConfirm = () => {
    if (renameDialog.currentName.trim()) {
      onRenamePage(renameDialog.pageId, renameDialog.currentName.trim());
    }
    setRenameDialog({ open: false, pageId: "", currentName: "" });
  };

  // Handle duplicate
  const handleDuplicateClick = () => {
    if (menuAnchor?.pageId) {
      onDuplicatePage(menuAnchor.pageId);
    }
    handleMenuClose();
  };

  // Handle delete click
  const handleDeleteClick = () => {
    const page = pages.find((p) => p.id === menuAnchor?.pageId);
    if (page) {
      setDeleteConfirm({
        open: true,
        pageId: page.id,
        pageName: page.name,
      });
    }
    handleMenuClose();
  };

  // Handle delete confirm
  const handleDeleteConfirm = () => {
    onDeletePage(deleteConfirm.pageId);
    setDeleteConfirm({ open: false, pageId: "", pageName: "" });
  };

  // Handle move
  const handleMove = (direction: "up" | "down") => {
    if (menuAnchor?.pageId) {
      onMovePage(menuAnchor.pageId, direction);
    }
    handleMenuClose();
  };

  const currentMenuIndex = menuAnchor ? getPageIndex(menuAnchor.pageId) : -1;

  // Width based on context - full width when embedded in CollapsiblePanel
  const panelWidth = embedded ? "100%" : isMobile ? "100%" : 220;

  return (
    <Box
      sx={{
        width: panelWidth,
        minWidth: embedded ? undefined : isMobile ? undefined : 180,
        borderRight: embedded ? 0 : isMobile ? 0 : 1,
        borderColor: "divider",
        display: "flex",
        flexDirection: "column",
        bgcolor: embedded ? "transparent" : "#fafafa",
        height: "100%",
      }}
    >
      {/* Header - hide when embedded */}
      {!embedded && (
        <Box
          sx={{
            p: 1.5,
            borderBottom: 1,
            borderColor: "divider",
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
          }}
        >
          <Typography
            variant="subtitle2"
            fontWeight={600}
            color="text.secondary"
          >
            Pagine ({pages.length})
          </Typography>
          <Tooltip title="Aggiungi pagina">
            <IconButton size="small" onClick={onAddPage} color="primary">
              <AddIcon fontSize="small" />
            </IconButton>
          </Tooltip>
        </Box>
      )}

      {/* Page List */}
      <List
        dense
        sx={{
          flex: 1,
          overflow: "auto",
          py: 0.5,
          // Hide scrollbar but keep functionality
          "&::-webkit-scrollbar": {
            width: 0,
            background: "transparent",
          },
          scrollbarWidth: "none", // Firefox
          msOverflowStyle: "none", // IE/Edge
        }}
      >
        {pages.map((page, index) => {
          const elementCount = getElementCount(page.id);
          const isSelected = page.id === currentPageId;

          return (
            <ListItem
              key={page.id}
              disablePadding
              sx={{
                mb: 0.5,
                mx: 0.5,
              }}
            >
              <ListItemButton
                selected={isSelected}
                onClick={() => onSelectPage(page.id)}
                sx={{
                  borderRadius: 1,
                  py: isMobile ? 1.5 : 1,
                  "&.Mui-selected": {
                    bgcolor: "primary.light",
                    color: "primary.contrastText",
                    "&:hover": {
                      bgcolor: "primary.main",
                    },
                    "& .MuiTypography-root": {
                      color: "inherit",
                    },
                    "& .MuiSvgIcon-root": {
                      color: "inherit",
                    },
                  },
                }}
              >
                <Box
                  sx={{
                    width: isMobile ? 28 : 32,
                    height: isMobile ? 36 : 40,
                    mr: 1.5,
                    borderRadius: 0.5,
                    bgcolor: isSelected ? "primary.dark" : "white",
                    border: 1,
                    borderColor: isSelected ? "primary.dark" : "grey.300",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    fontSize: "0.75rem",
                    fontWeight: 600,
                    color: isSelected ? "white" : "text.secondary",
                    flexShrink: 0,
                  }}
                >
                  {index + 1}
                </Box>
                <ListItemText
                  primary={page.name}
                  secondary={`${elementCount} elementi`}
                  primaryTypographyProps={{
                    variant: "body2",
                    fontWeight: isSelected ? 600 : 400,
                    noWrap: true,
                  }}
                  secondaryTypographyProps={{
                    variant: "caption",
                    color: isSelected ? "inherit" : "text.secondary",
                    sx: { opacity: isSelected ? 0.8 : 1 },
                  }}
                />
                <ListItemSecondaryAction>
                  <IconButton
                    edge="end"
                    size="small"
                    onClick={(e) => handleMenuOpen(e, page.id)}
                    sx={{
                      color: isSelected ? "white" : "text.secondary",
                      opacity: 0.7,
                      "&:hover": { opacity: 1 },
                    }}
                  >
                    <MoreIcon fontSize="small" />
                  </IconButton>
                </ListItemSecondaryAction>
              </ListItemButton>
            </ListItem>
          );
        })}
      </List>

      {/* Add Page Button (bottom) */}
      <Box sx={{ p: 1, borderTop: 1, borderColor: "divider" }}>
        <Button
          fullWidth
          variant="outlined"
          size={isMobile ? "medium" : "small"}
          startIcon={<AddIcon />}
          onClick={onAddPage}
          sx={{ textTransform: "none" }}
        >
          Nuova Pagina
        </Button>
      </Box>

      {/* Context Menu */}
      <Menu
        anchorEl={menuAnchor?.element}
        open={Boolean(menuAnchor)}
        onClose={handleMenuClose}
        anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
        transformOrigin={{ vertical: "top", horizontal: "right" }}
      >
        <MenuItem onClick={handleRenameClick}>
          <ListItemIcon>
            <EditIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>Rinomina</ListItemText>
        </MenuItem>
        <MenuItem onClick={handleDuplicateClick}>
          <ListItemIcon>
            <DuplicateIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>Duplica</ListItemText>
        </MenuItem>
        <Divider />
        <MenuItem
          onClick={() => handleMove("up")}
          disabled={currentMenuIndex <= 0}
        >
          <ListItemIcon>
            <MoveUpIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>Sposta Su</ListItemText>
        </MenuItem>
        <MenuItem
          onClick={() => handleMove("down")}
          disabled={currentMenuIndex >= pages.length - 1}
        >
          <ListItemIcon>
            <MoveDownIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>Sposta Giù</ListItemText>
        </MenuItem>
        <Divider />
        <MenuItem
          onClick={handleDeleteClick}
          disabled={pages.length <= 1}
          sx={{ color: pages.length > 1 ? "error.main" : "text.disabled" }}
        >
          <ListItemIcon>
            <DeleteIcon
              fontSize="small"
              color={pages.length > 1 ? "error" : "disabled"}
            />
          </ListItemIcon>
          <ListItemText>Elimina</ListItemText>
        </MenuItem>
      </Menu>

      {/* Rename Dialog */}
      <Dialog
        open={renameDialog.open}
        onClose={() =>
          setRenameDialog({ open: false, pageId: "", currentName: "" })
        }
        maxWidth="xs"
        fullWidth
        fullScreen={isMobile}
      >
        <DialogTitle>Rinomina Pagina</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            fullWidth
            label="Nome pagina"
            value={renameDialog.currentName}
            onChange={(e) =>
              setRenameDialog((prev) => ({
                ...prev,
                currentName: e.target.value,
              }))
            }
            onKeyDown={(e) => {
              if (e.key === "Enter") {
                handleRenameConfirm();
              }
            }}
            sx={{ mt: 1 }}
          />
        </DialogContent>
        <DialogActions sx={{ p: isMobile ? 2 : 1 }}>
          <Button
            onClick={() =>
              setRenameDialog({ open: false, pageId: "", currentName: "" })
            }
            fullWidth={isMobile}
          >
            Annulla
          </Button>
          <Button
            variant="contained"
            onClick={handleRenameConfirm}
            disabled={!renameDialog.currentName.trim()}
            fullWidth={isMobile}
          >
            Rinomina
          </Button>
        </DialogActions>
      </Dialog>

      {/* Delete Confirmation Dialog */}
      <Dialog
        open={deleteConfirm.open}
        onClose={() =>
          setDeleteConfirm({ open: false, pageId: "", pageName: "" })
        }
        maxWidth="xs"
        fullScreen={isMobile}
      >
        <DialogTitle>Elimina Pagina</DialogTitle>
        <DialogContent>
          <Typography>
            Sei sicuro di voler eliminare la pagina "{deleteConfirm.pageName}"?
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
            Tutti gli elementi sulla pagina verranno eliminati.
          </Typography>
        </DialogContent>
        <DialogActions sx={{ p: isMobile ? 2 : 1 }}>
          <Button
            onClick={() =>
              setDeleteConfirm({ open: false, pageId: "", pageName: "" })
            }
            fullWidth={isMobile}
          >
            Annulla
          </Button>
          <Button
            variant="contained"
            color="error"
            onClick={handleDeleteConfirm}
            fullWidth={isMobile}
          >
            Elimina
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}
