import {
  Button,
  CardCaption,
  Cell,
  Grid,
  Tab,
  Tabs,
  Thumbnail,
  TextInput,
} from "@sc/components/ui";
import { triggerHook } from "@sc/plugins";
import { AppConfig } from "@sc/modules/app";
import PropTypes from "prop-types";
import Radium from "radium";
import React, { Component } from "react";
import { Link } from "react-router-dom";
import style from "./style";

const typeMatches = {
  lead: ["lead", "webinar"],
  sales: ["sales", "content", "home"],
  event: ["event", "launch", "content"],
  oto: ["oto", "sales"],
  order: ["order", "checkout"],
  "thank you": ["thank you"],
  all: ["all"],
  blank: ["all"],
};

class TemplateItemHover extends Component {
  constructor(props) {
    super(props);
    this.changeTemplate = this.changeTemplate.bind(this);
  }

  static contextType = AppConfig;

  async changeTemplate() {
    const {
      // updateContent,
      updatePageContent,
      match,
      history,
      allCatalogDesignItems,
      pageId,
      content,
      settings,
      tab,
    } = this.props;
    // console.log(
    //   "Updating Template",
    //   { updateContent, match, allCatalogDesignItems, pageId, content },
    //   settings.page.type
    // );

    if (content) {
      const variables = {
        pageId: match.params.nodeId,
        content,
        type: tab,
      };

      let proceed = false;

      if (content.length > 7) {
        if (confirm("Are you sure you want to use this page as your template?"))
          proceed = true;
        else proceed = false;
      } else if (content.length < 7) proceed = true;

      if (proceed) {
        await updatePageContent({ variables });

        history.push(
          `/campaign/${match.params.campaignId}/${match.params.nodeId}/builder`
        );
      }
    }
  }

  render() {
    const { match, pageId } = this.props;

    if (!this.props.hidden) {
      return (
        <div style={style.templateItemHover.container}>
          <div
            style={{
              ...style.templateItemHover.container,
              ...style.templateItemHover.bg,
            }}
          />
          <div
            style={{
              ...style.templateItemHover.container,
              ...style.templateItemHover.content,
            }}
          >
            <Grid align="center" justify="center" style={{ height: "100%" }}>
              <Cell align="center">
                <Link
                  to={`/campaign/${match.params.campaignId}/${pageId}/builder/preview`}
                  target="_blank"
                >
                  <Button secondary large>
                    Preview Template
                  </Button>
                </Link>
                <br />
                <br />
                <Button onClick={this.changeTemplate} secondary large>
                  Use This Template
                </Button>
              </Cell>
            </Grid>
          </div>
        </div>
      );
    }
    return null;
  }
}

/**
 * This represents a single template
 * @param {object} props The props
 * @returns {function} The component
 */
class TemplateItem extends Component {
  constructor(props) {
    super(props);
    this.state = { templateItemHover: false };
    this.onMouseHover = this.onMouseHover.bind(this);
  }

  onMouseHover() {
    this.setState((prevState) => ({
      templateItemHover: !prevState.templateItemHover,
    }));
  }

  render() {
    const { id, description, image, name, page } = this.props.settings;

    return (
      <Cell key={id}>
        <div
          style={style.templateItem}
          onMouseEnter={this.onMouseHover}
          onMouseLeave={this.onMouseHover}
        >
          <div>
            <TemplateItemHover
              {...this.props}
              pageId={page ? page.id : false}
              content={page ? page.content : false}
              hidden={!this.state.templateItemHover}
            />
            <Thumbnail
              {...this.props}
              alt={description}
              style={{ borderRadius: 3 }}
              src={image}
            />
          </div>
        </div>
        <CardCaption style={{ padding: 10, textAlign: "center" }}>
          {name}
        </CardCaption>
      </Cell>
    );
  }
}

TemplateItem = Radium(TemplateItem);

/**
 * This is a sidebar that opens to reveal all the various
 * templates that can be applied to the associated page
 * @param {object} props The props
 * @returns {function} The component
 */
const TemplateSelection = (props) => {
  const [filter, setFilter] = React.useState("");

  return (
    <AppConfig.Consumer>
      {(settings) => {
        if (props.allCatalogDesignItems.loading)
          return (
            <div style={{ textAlign: "center" }}>
              <img src={settings.app.loadingImage} alt="Loading..." />
            </div>
          );
        if (props.allCatalogDesignItems.error)
          return (
            <div style={{ textAlign: "center" }}>
              <img src={settings.app.error} alt="Loading..." />
            </div>
          );

        console.log("TAB", props.tab);

        if (!props.hidden) {
          // what is the type of template we're filtering for? (tab)
          const tab = props.tab ? props.tab : "all";

          // what are the matching template types to include in your search
          let tabFilters = ["all"];
          if (!typeMatches.hasOwnProperty(tab)) {
            props.history.push("./all");
          } else {
            tabFilters = typeMatches[tab];
          }

          // filter catalog items for any of those types
          const pluginItems = triggerHook("onListItems", {
            id: "template",
            type: "designs",
          });
          const catalogItems = props.allCatalogDesignItems.catalogItems;

          const items = [...pluginItems, ...catalogItems]
            .filter(
              ({ name }) =>
                name.toLowerCase().indexOf(filter.toLowerCase()) > -1
            )
            .filter(
              (itm) => tabFilters.indexOf(itm.categories) > -1 || tab === "all"
            );
          // console.log({ catalogItems, pluginItems, items });

          // build a TemplateItem object from that
          return (
            <div>
              <div
                style={{
                  backgroundColor: "rgb(245,245,245)",
                  borderBottom: "1px solid rgb(238, 238, 238)",
                }}
              >
                <h2
                  style={{ textAlign: "center", padding: 20, paddingTop: 40 }}
                >
                  Please choose a template for this page
                </h2>
                {/* {props.title ? <h1>Choose a template for this page</h1> : null} */}
                <div style={{ width: 650, margin: "0 auto" }}>
                  <TextInput
                    placeholder="Search for a template..."
                    onChange={(e) => setFilter(e.target.value)}
                    value={filter}
                    style={{ backgroundColor: "white" }}
                  />
                </div>
                <Tabs transparent style={{ padding: "35px 0 0" }}>
                  <Tab name="all" href="all" currentTab={tab}>
                    All Pages
                  </Tab>
                  <Tab name="lead" href="lead" currentTab={tab}>
                    Lead Capture
                  </Tab>
                  <Tab name="sales" href="sales" currentTab={tab}>
                    Sales Pages
                  </Tab>
                  <Tab name="event" href="event" currentTab={tab}>
                    Event Pages
                  </Tab>
                  <Tab name="oto" href="oto" currentTab={tab}>
                    Special Offer
                  </Tab>
                  <Tab name="order" href="order" currentTab={tab}>
                    Checkout Pages
                  </Tab>
                  <Tab name="thank you" href="thank you" currentTab={tab}>
                    Thank You Pages
                  </Tab>
                </Tabs>
              </div>
              <Grid justify="center" wrap style={{ padding: 25 }}>
                {items.map((template, key) => (
                  <TemplateItem key={key} {...props} settings={template} />
                ))}
              </Grid>
            </div>
          );
        }
      }}
    </AppConfig.Consumer>
  );
};

TemplateSelection.propTypes = {
  /** Boolean whether or not to display the section */
  hidden: PropTypes.bool,
  tab: PropTypes.string,
};

TemplateSelection.defaultProps = {
  hidden: false,
  tab: "all",
};

export default TemplateSelection;
