import {
  useState,
  useRef,
  useCallback,
  useEffect,
  type ReactNode,
} from "react";
import { Box, IconButton, Tooltip, Typography, alpha } from "@mui/material";
import {
  ChevronLeft as CollapseLeftIcon,
  ChevronRight as CollapseRightIcon,
  DragIndicator as DragIcon,
} from "@mui/icons-material";

// Data transfer type for panel drag and drop
export const PANEL_DRAG_TYPE = "application/x-panel-id";

interface ResizablePanelProps {
  /** Unique panel identifier */
  id: string;
  /** Panel title shown in header and tooltip when collapsed */
  title: string;
  /** Icon shown when panel is collapsed */
  icon: ReactNode;
  /** Panel position - determines collapse button direction */
  position: "left" | "right";
  /** Flex value for vertical sizing (default 1) */
  flex?: number;
  /** Whether the panel is currently collapsed */
  collapsed: boolean;
  /** Panel width when collapsed (icon strip) */
  collapsedWidth?: number;
  /** Callback when flex changes during vertical resize */
  onFlexChange?: (flex: number) => void;
  /** Callback when collapse state changes */
  onToggleCollapse: () => void;
  /** Panel content */
  children: ReactNode;
  /** Optional badge content (e.g., count) */
  badge?: ReactNode;
  /** Whether this is the last panel in the sidebar (no bottom resize handle) */
  isLast?: boolean;
}

export default function ResizablePanel({
  id,
  title,
  icon,
  position,
  flex = 1,
  collapsed,
  collapsedWidth = 44,
  onFlexChange,
  onToggleCollapse,
  children,
  badge,
  isLast = false,
}: ResizablePanelProps) {
  const [isResizingHeight, setIsResizingHeight] = useState(false);
  const [isDragging, setIsDragging] = useState(false);
  const panelRef = useRef<HTMLDivElement>(null);
  const startYRef = useRef(0);
  const startHeightRef = useRef(0);
  const startFlexRef = useRef(flex);

  const CollapseIcon =
    position === "left" ? CollapseLeftIcon : CollapseRightIcon;
  const ExpandIcon = position === "left" ? CollapseRightIcon : CollapseLeftIcon;

  // Handle drag start - make header draggable
  const handleDragStart = useCallback(
    (e: React.DragEvent) => {
      e.dataTransfer.setData(PANEL_DRAG_TYPE, id);
      e.dataTransfer.effectAllowed = "move";
      setIsDragging(true);
    },
    [id],
  );

  // Handle drag end
  const handleDragEnd = useCallback(() => {
    setIsDragging(false);
  }, []);

  // Handle mouse down on vertical resize handle
  const handleResizeHeightStart = useCallback(
    (e: React.MouseEvent) => {
      e.preventDefault();
      if (!panelRef.current) return;
      setIsResizingHeight(true);
      startYRef.current = e.clientY;
      startHeightRef.current = panelRef.current.offsetHeight;
      startFlexRef.current = flex;
    },
    [flex],
  );

  // Handle mouse move during vertical resize
  useEffect(() => {
    if (!isResizingHeight || !onFlexChange) return;

    const handleMouseMove = (e: MouseEvent) => {
      const deltaY = e.clientY - startYRef.current;
      const heightRatio =
        (startHeightRef.current + deltaY) / startHeightRef.current;
      const newFlex = Math.max(0.2, startFlexRef.current * heightRatio);
      onFlexChange(newFlex);
    };

    const handleMouseUp = () => {
      setIsResizingHeight(false);
    };

    document.addEventListener("mousemove", handleMouseMove);
    document.addEventListener("mouseup", handleMouseUp);

    return () => {
      document.removeEventListener("mousemove", handleMouseMove);
      document.removeEventListener("mouseup", handleMouseUp);
    };
  }, [isResizingHeight, onFlexChange]);

  // Collapsed state - show icon strip (also draggable)
  if (collapsed) {
    return (
      <Box
        ref={panelRef}
        data-panel-id={id}
        draggable
        onDragStart={handleDragStart}
        onDragEnd={handleDragEnd}
        sx={{
          width: collapsedWidth,
          minWidth: collapsedWidth,
          flex: flex,
          minHeight: 80,
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          bgcolor: (theme) => alpha(theme.palette.primary.main, 0.03),
          borderBottom: 1,
          borderColor: "divider",
          py: 1,
          flexShrink: 1,
          flexGrow: flex,
          cursor: "grab",
          opacity: isDragging ? 0.5 : 1,
          transition: "opacity 0.2s",
          "&:active": {
            cursor: "grabbing",
          },
        }}
      >
        {/* Expand button */}
        <Tooltip
          title={`Espandi: ${title}`}
          placement={position === "left" ? "right" : "left"}
        >
          <IconButton
            size="small"
            onClick={(e) => {
              e.stopPropagation();
              onToggleCollapse();
            }}
            sx={{
              mb: 1,
              bgcolor: (theme) => alpha(theme.palette.primary.main, 0.08),
              "&:hover": {
                bgcolor: (theme) => alpha(theme.palette.primary.main, 0.15),
              },
            }}
          >
            <ExpandIcon fontSize="small" />
          </IconButton>
        </Tooltip>

        {/* Panel icon with tooltip */}
        <Tooltip
          title={`${title} - Trascina per spostare`}
          placement={position === "left" ? "right" : "left"}
        >
          <Box
            sx={{
              p: 1,
              borderRadius: 1,
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              gap: 0.5,
            }}
          >
            <Box
              sx={{
                color: "primary.main",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              {icon}
            </Box>
            {badge && (
              <Box
                sx={{
                  bgcolor: "primary.main",
                  color: "primary.contrastText",
                  borderRadius: "10px",
                  px: 0.75,
                  py: 0.25,
                  fontSize: "0.6rem",
                  fontWeight: 600,
                  minWidth: 16,
                  textAlign: "center",
                }}
              >
                {badge}
              </Box>
            )}
          </Box>
        </Tooltip>

        {/* Vertical title */}
        <Typography
          variant="caption"
          sx={{
            writingMode: "vertical-rl",
            textOrientation: "mixed",
            transform: "rotate(180deg)",
            color: "text.secondary",
            mt: 2,
            letterSpacing: 0.5,
            fontWeight: 500,
            fontSize: "0.7rem",
          }}
        >
          {title}
        </Typography>

        {/* Drag indicator at bottom */}
        <Box sx={{ mt: "auto", mb: 1, color: "text.disabled" }}>
          <DragIcon fontSize="small" />
        </Box>
      </Box>
    );
  }

  // Expanded state
  return (
    <Box
      ref={panelRef}
      data-panel-id={id}
      sx={{
        width: "100%",
        flex: flex,
        minHeight: 120,
        display: "flex",
        flexDirection: "column",
        borderBottom: 1,
        borderColor: "divider",
        bgcolor: "background.paper",
        position: "relative",
        flexShrink: 1,
        flexGrow: flex,
        opacity: isDragging ? 0.5 : 1,
        transition: "opacity 0.2s",
      }}
    >
      {/* Header with collapse button - DRAGGABLE */}
      <Box
        draggable
        onDragStart={handleDragStart}
        onDragEnd={handleDragEnd}
        sx={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          px: 1,
          py: 0.75,
          borderBottom: 1,
          borderColor: "divider",
          bgcolor: (theme) => alpha(theme.palette.primary.main, 0.03),
          minHeight: 40,
          cursor: "grab",
          userSelect: "none",
          "&:active": {
            cursor: "grabbing",
          },
        }}
      >
        <Box
          sx={{
            display: "flex",
            alignItems: "center",
            gap: 0.75,
            minWidth: 0,
            flex: 1,
          }}
        >
          {/* Drag handle indicator */}
          <Tooltip title="Trascina per spostare">
            <Box
              sx={{
                color: "text.disabled",
                display: "flex",
                "&:hover": { color: "text.secondary" },
              }}
            >
              <DragIcon fontSize="small" />
            </Box>
          </Tooltip>
          <Box sx={{ color: "primary.main", display: "flex", flexShrink: 0 }}>
            {icon}
          </Box>
          <Typography
            variant="subtitle2"
            fontWeight={600}
            sx={{
              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
              fontSize: "0.8rem",
            }}
          >
            {title}
          </Typography>
          {badge && (
            <Box
              sx={{
                bgcolor: "primary.main",
                color: "primary.contrastText",
                borderRadius: "10px",
                px: 0.6,
                py: 0.15,
                fontSize: "0.6rem",
                fontWeight: 600,
                minWidth: 16,
                textAlign: "center",
                flexShrink: 0,
              }}
            >
              {badge}
            </Box>
          )}
        </Box>
        <Tooltip title="Comprimi">
          <IconButton
            size="small"
            onClick={(e) => {
              e.stopPropagation();
              onToggleCollapse();
            }}
            sx={{ flexShrink: 0 }}
          >
            <CollapseIcon fontSize="small" />
          </IconButton>
        </Tooltip>
      </Box>

      {/* Content */}
      <Box
        sx={{
          flex: 1,
          display: "flex",
          flexDirection: "column",
          overflow: "hidden",
        }}
      >
        {children}
      </Box>

      {/* Vertical resize handle (only show if not last panel and onFlexChange is provided) */}
      {!isLast && onFlexChange && (
        <Box
          onMouseDown={handleResizeHeightStart}
          sx={{
            position: "absolute",
            bottom: -4,
            left: 0,
            right: 0,
            height: 8,
            cursor: "row-resize",
            zIndex: 1000,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            "&:hover": {
              "& .resize-indicator-v": {
                opacity: 1,
                bgcolor: "primary.main",
              },
            },
            ...(isResizingHeight && {
              "& .resize-indicator-v": {
                opacity: 1,
                bgcolor: "primary.main",
              },
            }),
          }}
        >
          <Box
            className="resize-indicator-v"
            sx={{
              width: 50,
              height: 4,
              borderRadius: 1,
              bgcolor: "divider",
              opacity: 0.7,
              transition: "opacity 0.15s, background-color 0.15s",
            }}
          />
        </Box>
      )}
    </Box>
  );
}
