import styled from "@emotion/styled";
import * as _ from "lodash";
import { inject, observer } from "mobx-react";
import React from "react";
import { TiDocumentText } from "react-icons/ti";
import {
  LIGHT_PRIMARY_THREE,
  LIGHT_SECONDARY_FOUR,
} from "../../../shared/colors";
import { SlideIdea } from "../../../shared/types";
import { StoreProps } from "../../platform/SlideshowStore";
import withPlatform, { PlatformProps } from "../../platform/withPlatform";
import Resizer from "./Resizer";
import {
  currentKeys,
  CurrentScreen,
  getCanvasPosition,
} from "./windowListeners";

const prefilledText = [{ type: "paragraph", children: [{ text: "" }] }];

type Props = {
  slideIdea: SlideIdea;
} & PlatformProps &
  StoreProps;

function SlideObjectIdea(props: Props) {
  return (
    <Resizer
      elementId={props.slideIdea.id}
      top={props.slideIdea.y}
      left={props.slideIdea.x}
      width={props.slideIdea.width}
      height={props.slideIdea.height}
      visible={props.store.selectedSlideElement.get() === props.slideIdea.id}
      store={props.store}
    >
      <BoardItem
        onClick={(e) => {
          props.store.selectedSlideElement.set(props.slideIdea.id);
          if (
            CurrentScreen.initialClickX === e.screenX &&
            CurrentScreen.initialClickY === e.screenY &&
            !e.shiftKey
          ) {
            // Click without moving
            props.store.showBoardModal.set(props.slideIdea.id);
          }
        }}
        onMouseDown={(e) => {
          if (e.button !== 1 && !(e.button === 0 && currentKeys["Space"])) {
            const canvasPosition = getCanvasPosition(e, props.store);
            CurrentScreen.canvasX = canvasPosition.x;
            CurrentScreen.canvasY = canvasPosition.y;
            CurrentScreen.initialClickX = e.screenX;
            CurrentScreen.initialClickY = e.screenY;
            props.store.currentDragElement.set(props.slideIdea.id);
            e.stopPropagation();
          }
        }}
        empty={!props.slideIdea.title}
      >
        {!!props.slideIdea.description &&
          !_.isEqual(props.slideIdea.description, prefilledText) && (
            <TiDocumentText style={{ marginRight: 8 }} />
          )}
        <BoardTitle>{props.slideIdea.title || "Untitled"}</BoardTitle>
      </BoardItem>
    </Resizer>
  );
}

export default withPlatform(inject("store")(observer(SlideObjectIdea)));

const BoardItem = styled.div<{ empty: boolean }>`
  position: relative;
  background-color: ${LIGHT_PRIMARY_THREE};
  display: flex;
  align-items: center;
  width: calc(100% - 16px);
  height: calc(100% - 16px);
  border-radius: 4px;
  box-shadow: 0px 0px 0px 1px rgba(15, 15, 15, 0.1),
    0px 2px 4px rgba(15, 15, 15, 0.1);
  padding: 8px;
  cursor: grab;
  ${(props) => props.empty && `color: ${LIGHT_SECONDARY_FOUR};`}
`;

const BoardTitle = styled.div`
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
`;
