import * as React from "react";
import ZoomOutIcon from "@mui/icons-material/ZoomOut";
import ZoomInIcon from "@mui/icons-material/ZoomIn";
import OpenInFullIcon from "@mui/icons-material/OpenInFull";
import { ToolbarProps, MIN_ZOOM, MAX_ZOOM, TOOLBAR_HEIGHT } from "./Interface";

export function Toolbar({ zoom, totalWidth }: ToolbarProps) {
  const zoomPercent = Math.round((zoom.transformMatrix?.scaleX ?? 1) * 100);

  return (
    <div
      style={{
        height: "auto",
        minHeight: TOOLBAR_HEIGHT,
        display: "flex",
        justifyContent: "flex-end",
        alignItems: "center",
        flexWrap: "wrap",
        padding: "6px 12px",
        gap: 8,
        background: "#ffffff",
        borderBottom: "1px solid #e8ecf0",
        boxSizing: "border-box",
      }}
    >
      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: 2,
          height: 36,
          background: "#ffffff",
          border: "1.5px solid #dde2e8",
          borderRadius: 12,
          padding: "0 8px",
          boxSizing: "border-box",
        }}
      >
        <button
          title="Zoom Out"
          onClick={() => {
            const current = zoom.transformMatrix?.scaleX ?? 1;
            const next = Math.max(MIN_ZOOM, current - 0.1);
            zoom.scale({ scaleX: next / current, scaleY: next / current });
          }}
          style={iconButtonStyle}
        >
          <ZoomOutIcon style={{ fontSize: 19 }} />
        </button>

        <span
          style={{
            minWidth: 46,
            textAlign: "center",
            fontSize: "0.8rem",
            fontWeight: 600,
            color: "#37474f",
            userSelect: "none",
            fontFamily: "inherit",
            letterSpacing: "0.01em",
            display: totalWidth < 360 ? "none" : "inline",
          }}
        >
          {zoomPercent}%
        </span>

        <button
          title="Zoom In"
          onClick={() => {
            const current = zoom.transformMatrix?.scaleX ?? 1;
            const next = Math.min(MAX_ZOOM, current + 0.1);
            zoom.scale({ scaleX: next / current, scaleY: next / current });
          }}
          style={iconButtonStyle}
        >
          <ZoomInIcon style={{ fontSize: 19 }} />
        </button>

        <div style={{ width: 1, height: 18, background: "#dde2e8", margin: "0 4px" }} />

        <button
          title="Reset to 100%"
          onClick={zoom.reset}
          style={iconButtonStyle}
        >
          <OpenInFullIcon style={{ fontSize: 15 }} />
        </button>
      </div>
    </div>
  );
}

const iconButtonStyle: React.CSSProperties = {
  display: "flex",
  alignItems: "center",
  justifyContent: "center",
  width: 44,
  height: 44,
  border: "none",
  background: "transparent",
  cursor: "pointer",
  borderRadius: "50%",
  color: "#546e7a",
  padding: 0,
};
