import React, { useState, useEffect } from "react";
import Box from "@mui/material/Box";
import Drawer from "@mui/material/Drawer";
import { Button } from "../Button";
import List from "@mui/material/List";
import Divider from "@mui/material/Divider";
import ListItem from "@mui/material/ListItem";
import ListItemButton from "@mui/material/ListItemButton";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import InboxIcon from "@mui/icons-material/MoveToInbox";
import MailIcon from "@mui/icons-material/Mail";
import "./Panel.styles.scss";

export function Panel({
  className,
  title,
  size,
  anchor = "right",
  open,
  setIsOpen,
  children,
  onClose,
  primaryButtonLabel,
  onPrimaryButtonClick,
  secondaryButtonLabel,
  onSecondaryButtonClick,
  primaryButtonProps,
  secondaryButtonProps,
  width,
  zIndex = 1500,
  customFooterContent,
  resizable,
  minWidth = 375,
  maxWidth,
  onResize,
  ...args
}) {
  const toggleDrawer = (anchor, isOpen) => (event) => {
    if (
      event.type === "keydown" &&
      (event.key === "Tab" || event.key === "Shift")
    ) {
      return;
    }
    if (onClose) {
      onClose();
    }
    setIsOpen(isOpen);
  };

  const [drawerWidth, setDrawerWidth] = useState(width ? parseInt(width) : 526);

  useEffect(() => {
    setDrawerWidth(width ? parseInt(width) : 526);
  }, [width]);

  const getSize = (size) => {
    switch (size) {
      case "medium":
        return "impact_drawer_container_medium";
      default:
        return "impact_drawer_container_large";
    }
  };

  const handleResizeMouseDown = (e) => {
    e.preventDefault();
    const startX = e.clientX;
    const startWidth = drawerWidth;
    const min = minWidth;
    const max = maxWidth ?? window.innerWidth - 100;

    const onMouseMove = (moveEvent) => {
      const delta = moveEvent.clientX - startX;
      // Left-anchored: handle is on the right edge, dragging right grows it.
      // Right-anchored: handle is on the left edge, dragging left grows it.
      let newWidth = anchor === "left" ? startWidth + delta : startWidth - delta;
      if (newWidth < min) newWidth = min;
      if (newWidth > max) newWidth = max;
      setDrawerWidth(newWidth);
      onResize?.(newWidth);
    };

    const onMouseUp = () => {
      document.body.classList.remove("no-select");
      document.removeEventListener("mousemove", onMouseMove);
      document.removeEventListener("mouseup", onMouseUp);
    };

    document.body.classList.add("no-select");
    document.addEventListener("mousemove", onMouseMove);
    document.addEventListener("mouseup", onMouseUp);
  };

  const getCurrentWidth = () => {
    if (resizable) return `${drawerWidth}px`;
    if (width) return `${width}px`;
    return undefined;
  };

  const resizerHandle = resizable ? (
    <div
      className={`panel-resizer ${
        anchor === "left" ? "panel-resizer-right" : "panel-resizer-left"
      }`}
      onMouseDown={handleResizeMouseDown}
    />
  ) : null;

  if (!secondaryButtonLabel && !primaryButtonLabel) {
    return (
      <Drawer
        anchor={anchor}
        open={open}
        onClose={toggleDrawer(anchor, false)}
        sx={{
          "& .MuiDrawer-paper": {
            zIndex: `${zIndex}`,
            overflow: "visible",
          },
        }}
      >
        <div
          className={`impact_drawer_container ${getSize(size)} ${className}`}
          style={{ width: getCurrentWidth() }}
        >
          {resizerHandle}
          <div className="impact_drawer_header">
            <div className="impact_drawer_heading">{title}</div>
            <span
              role="button"
              className="close_icon"
              onClick={toggleDrawer(anchor, false)}
              tabIndex={0}
              onKeyDown={(e) => {
                if (e.key === "Enter" || e.key === " ") {
                  e.preventDefault();
                  toggleDrawer(anchor, false)(e);
                }
              }}
            ></span>
          </div>
          <div
            className="impact_drawer_body"
            style={{ height: "calc(100% - 40px)" }}
          >
            {children}
          </div>
        </div>
      </Drawer>
    );
  }

  return (
    <Drawer
      anchor={anchor}
      open={open}
      onClose={toggleDrawer(anchor, false)}
      sx={{
        "& .MuiDrawer-paper": {
          zIndex: `${zIndex}`,
          overflow: "visible",
        },
      }}
      {...args}
    >
      <div
        className={`impact_drawer_container ${getSize(size)} ${className}`}
        style={{ width: getCurrentWidth() }}
      >
        {resizerHandle}
        <div className="impact_drawer_header">
          <div className="impact_drawer_heading">{title}</div>
          <span
            role="button"
            className="close_icon"
            onClick={toggleDrawer(anchor, false)}
            tabIndex={0}
            onKeyDown={(e) => {
              if (e.key === "Enter" || e.key === " ") {
                e.preventDefault();
                toggleDrawer(anchor, false)(e);
              }
            }}
          ></span>
        </div>
        <div className="impact_drawer_body">{children}</div>
        <div className="impact_drawer_footer">
          {customFooterContent ? customFooterContent : null}
          <div className="impact_drawer_footer_right_container">
            {secondaryButtonLabel && (
              <Button
                label={secondaryButtonLabel}
                variant="url"
                onClick={onSecondaryButtonClick}
                {...secondaryButtonProps}
              >
                {secondaryButtonLabel}
              </Button>
            )}
            {primaryButtonLabel && (
              <Button
                label={primaryButtonLabel}
                onClick={onPrimaryButtonClick}
                {...primaryButtonProps}
              >
                {primaryButtonLabel}
              </Button>
            )}
          </div>
        </div>
      </div>
    </Drawer>
  );
}
