/* eslint-disable react/prop-types */
import React from "react";
import { BugButtonSubmissionContainer } from "../BugButtonApp";
import styled from "styled-components";
import Box from "@material-ui/core/Box";
import { DraggablePin } from "./DraggablePin";
import Debug from "debug";
import useHotkeys from "use-hotkeys";

const debug = Debug("userbugreport:PinBoard");

/**
 * Drop things here.
 */
const DropLayer = styled(Box)`
  width: 100%;
  height: 100%;
  z-index: ${(props) => props.theme.zIndex.tooltip};
`;

/**
 * Props to configure our pinboard.
 */
export interface PinBoardProps {
  style?: React.CSSProperties;
  pinStyle?: React.CSSProperties;
  noteStyle?: React.CSSProperties;
  readonly?: boolean;
}

export type Position = {
  x: number;
  y: number;
};

/**
 * The pin board user interface. Lay this over screen shots to mark
 * errors visually.
 */
export const PinBoard: React.FC<PinBoardProps> = (props: PinBoardProps) => {
  debug("rendering", props);

  // this is our real state -- all the pins being displayed.
  const {
    submission,
    selectNote,
    deleteSelectedNotes,
  } = BugButtonSubmissionContainer.useContainer();

  // capture the drag drop bounds
  const dragConstraints = React.useRef<HTMLElement>();
  const [position, setPosition] = React.useState<Position>();

  // keyboard handling with a hook, sorta awesome
  useHotkeys(
    (key) => {
      debug(key);
      deleteSelectedNotes();
    },
    ["backspace", "del", "delete"],
    [submission.notes]
  );

  React.useEffect(() => {
    const bounds = dragConstraints.current.getBoundingClientRect();
    setPosition({
      x: bounds.left,
      y: bounds.top,
    });
  }, [dragConstraints]);

  // and finally render
  return (
    <DropLayer
      style={props.style}
      ref={dragConstraints}
      onClick={() => selectNote(undefined)}
    >
      {submission.notes.map((p) => (
        <DraggablePin
          {...props}
          key={p.id}
          {...p}
          offset={position}
          dragConstraints={dragConstraints}
        />
      ))}
    </DropLayer>
  );
};
