import _ from "lodash";
import PropTypes from "prop-types";
import React, { Component } from "react";
import { FontIcon, ListItem, Menu } from "@sc/components/ui";
import { listChildren } from "@sc/modules/v2/Editor/actions";

import style from "./style";

const MoreListItems = (props) => {
  if (props.dropDownItems) {
    return props.dropDownItems.map((itm, key) =>
      itm.id === "divider" ? (
        <div key={key} style={style.divider} />
      ) : (
        <ListItem
          key={key}
          onClick={(e) => {
            e.stopPropagation();
            props.onDropDownChange(itm.id);
          }}
        >
          {itm.text}
        </ListItem>
      )
    );
  }
  return null;
};

class DragHandle extends Component {
  constructor(props) {
    super(props);

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(action) {
    const {
      settings,
      removeItem,
      duplicateItem,
      addThisAfterThat,
      pageContent,
    } = this.props;

    switch (action) {
      case "duplicate":
        duplicateItem(settings.id);
        break;
      case "delete":
        removeItem(settings.id);
        break;
      case "save":
        break;
      case "COPY": {
        // generate JSON
        const df = _.head(pageContent.filter((itm) => itm.id === settings.id));
        const cnt = listChildren(pageContent, settings.id);
        // console.log(cnt);
        const clipboard = JSON.stringify(cnt);

        // add to local storage
        if (typeof window === "object") {
          window.sessionStorage.setItem("clipboard", clipboard);
          alert("The Element Has Been Copied");
        }

        console.log(clipboard);
        break;
      }
      case "PASTE": {
        // grab from local storage
        const clipboard = JSON.parse(sessionStorage.getItem("clipboard"));
        // add to canvas below this section
        addThisAfterThat(clipboard, settings.id);
        break;
      }
      default:
        break;
    }
  }

  render() {
    const {
      settings,
      showProperties,
      color,
      objCoordinates,
      parentCoordinates,
      ecCoordinates,
      customComponent,
    } = this.props;

    const type = [
      settings.type[0].toUpperCase(),
      ...settings.type.slice(1),
    ].join("");

    const distFromTop = Math.abs(ecCoordinates.top - objCoordinates.top);
    const distFromParent = Math.abs(parentCoordinates.top - objCoordinates.top);
    const offset =
      distFromTop < 22 || distFromParent < 22
        ? { marginTop: 0 }
        : { marginTop: -22 };

    const objectHandle = {
      active: {
        ...style.objectHandleNormal,
        ...offset,
        backgroundColor: color,
        borderColor: color,
        color: "white",
        fontWeight: "bold",
        borderTopLeftRadius: 2,
        borderTopRightRadius: 2,
        cursor: "grab",
        ..._.get(this.props, "objectHandleStyle.active", {}),
      },
      hover: {
        ...style.objectHandleNormal,
        ...offset,
        color,
        cursor: "grab",
        ..._.get(this.props, "objectHandleStyle.hover", {}),
      },
    };

    let label = settings.type;
    if (_.has(this.props, "label")) label = this.props.label;
    if (_.has(settings, "label")) label = settings.label;

    return (
      <>
        {customComponent}
        <div style={objectHandle[settings.state]}>
          {settings.properties.width < 110 ||
          objCoordinates.width < 110 ? null : (
            <span style={{ ...style.dragHandleText }}>
              {label.toUpperCase()}
            </span>
          )}
          {settings.state === "active" ? (
            <div style={{ display: "inline-block" }}>
              <FontIcon
                onClick={showProperties}
                style={style.gearIcon}
                title={`Show ${type} Properties`}
              >
                settings
              </FontIcon>
              {settings.parent ? (
                <div
                  style={{
                    display: "inline",
                    position: "absolute",
                    marginLeft: 7,
                    marginTop: -8,
                    cursor: "pointer",
                  }}
                >
                  <Menu
                    position="BOTTOM_RIGHT"
                    id="avatar-menu"
                    icon={
                      <span id="avatar-menu">
                        <FontIcon
                          className="arrdropdown"
                          style={{ zoom: "90%", color: "#666" }}
                        >
                          arrow_drop_down
                        </FontIcon>
                      </span>
                    }
                  >
                    {/* <div style={style.divider} /> */}
                    <ListItem
                      onClick={(e) => {
                        // e.stopPropagation();
                        this.handleChange("COPY");
                      }}
                    >
                      Copy to Clipboard
                    </ListItem>

                    {window.sessionStorage.hasOwnProperty("clipboard") ? (
                      <ListItem
                        onClick={(e) => {
                          // e.stopPropagation();
                          this.handleChange("PASTE");
                        }}
                      >
                        Paste Below
                      </ListItem>
                    ) : (
                      <div />
                    )}
                    <div style={style.divider} />
                    <MoreListItems {...this.props} />
                    <ListItem
                      onClick={(e) => {
                        e.stopPropagation();
                        this.handleChange("duplicate");
                      }}
                    >
                      Duplicate
                    </ListItem>
                    <ListItem
                      onClick={(e) => {
                        e.stopPropagation();
                        this.handleChange("delete");
                      }}
                    >
                      Delete
                    </ListItem>
                  </Menu>
                </div>
              ) : null}
            </div>
          ) : null}
        </div>
      </>
    );
  }
}

DragHandle.propTypes = {
  showProperties: PropTypes.func.isRequired,
  showOverlay: PropTypes.bool,
  isResizable: PropTypes.bool,
  color: PropTypes.string,
  // dropDownItems: PropTypes.array
};

DragHandle.defaultProps = {
  dropDownItems: false,
};

export default DragHandle;
