/* eslint-disable react/display-name */
import React, { PointerEventHandler } from "react";
import { FaMapPin } from "react-icons/fa";
import styled, { ThemeProvider } from "styled-components";
import { useTheme } from "@material-ui/core/styles";
import Debug from "debug";
import { motion } from "framer-motion";
import { Selectable } from "../Props";
const debug = Debug("userbugreport:Pin");

/**
 * Share the iocn for use in other buttons to manage pins.
 */
export const PinIcon = FaMapPin;

/**
 * Sized control root grid.
 */
const Root = styled.div`
  display: grid;
  grid-template-columns: ${(props) => props.theme.spacing(4)}px;
  grid-template-rows: ${(props) => props.theme.spacing(4)}px;
  grid-template-areas: "display";
`;

/**
 * The pin will fill in the area and sit high in the Z.
 */
const MapPin = styled(FaMapPin)`
  width: 100%;
  height: 100%;
  grid-area: display;
  color: ${(props) => props.theme.palette.secondary.main};
  z-index: ${(props) => props.theme.zIndex.tooltip - 1};
`;

/**
 * Shadow of the pin set up for animation.
 */
const Shadow = styled(motion.div)`
  grid-area: display;
  z-index: ${(props) => props.theme.zIndex.tooltip - 1};
`;

/**
 * Props for our friend the pin.
 */
export interface PinProps extends Selectable {
  onClick?: PointerEventHandler;
  onPointerDown?: PointerEventHandler;
  style?: React.CSSProperties;
}

/**
 * It's a pin graphic, with drag and drop affordance.
 */
export const Pin = React.forwardRef<HTMLElement, PinProps>(
  (props: PinProps, ref) => {
    debug("render", props);
    const theme = useTheme();

    const shadows = {
      selected: {
        opacity: 1,
        marginLeft: theme.shadows[5].split(" ")[1],
        filter: `blur(${theme.shadows[5].split(" ")[2]})`,
      },
      notSelected: {
        opacity: 0,
        marginLeft: 0,
        filter: "blur(0)",
      },
    };

    return (
      <ThemeProvider theme={theme}>
        <Root
          ref={ref}
          onClick={(e) => {
            e.stopPropagation();
            props?.onClick(e);
          }}
          onPointerDown={props.onPointerDown}
        >
          <MapPin style={props.style} />
          <Shadow
            animate={props.selected ? "selected" : "notSelected"}
            variants={shadows}
            style={props.style}
          >
            <MapPin style={props.style} />
          </Shadow>
        </Root>
      </ThemeProvider>
    );
  }
);
