import {
  Button,
  Cell,
  FontIcon,
  Grid,
  ListItem,
  Menu,
} from "@sc/components/ui";
import { AppConfig } from "@sc/modules/app";
import _ from "lodash";
import React, { Component } from "react";
import { Link } from "react-router-dom";
import slugify from "slugify";
// import { app } from "../../../config";
import { objects, RenamableTitle, style } from "../shared";
// import { UpDownControls } from "./UpDownControls";
import { triggerHook } from "@sc/plugins";

class CampaignLegendObject extends Component {
  constructor(props) {
    super(props);

    this.state = {
      percentage: 0,
      slug: _.get(props, "settings.page.slug", false),
      isActive: false,
      loading: false,
      settings: props.settings,
      numberActive: false,
    };

    this.renameObject = this.renameObject.bind(this);
    this.deleteObject = this.deleteObject.bind(this);
    this.makeThisMyHomePage = this.makeThisMyHomePage.bind(this);
    this.makeThisMy404Page = this.makeThisMy404Page.bind(this);
    this.makeThisATemplate = this.makeThisATemplate.bind(this);
    this.showSlug = this.showSlug.bind(this);
    this.hideSlug = this.hideSlug.bind(this);
    this.cloneObject = this.cloneObject.bind(this);
  }

  static contextType = AppConfig;

  makeThisMyHomePage() {
    // what is the id of the domain for this campaign?
    const domainId = this.props.getCampaignQuery.campaign.domain.id;
    const pageId = this.props.settings.page.id;

    if (domainId) {
      this.props
        .makeThisMyHomePage({
          variables: {
            pageId,
            domainId,
          },
        })
        .then((json) => {
          console.log(json);
          // this.props.getCampaignQuery.refetch();
          alert(
            `Your Home Page settings have been updated.  Please re-publish the "${json.data.updateDomain.homePage.name}" page for it to take effect for your website visitors.`
          );

          window.location.reload();
        });
    } else {
      alert("No Domain Has Been Set For This Campaign");
    }
  }

  makeThisMy404Page() {
    // what is the id of the domain for this campaign?
    const domainId = this.props.getCampaignQuery.campaign.domain.id;
    const pageId = this.props.settings.page.id;

    if (domainId) {
      this.props
        .makeThisMyErrorPage({
          variables: {
            pageId,
            domainId,
          },
        })
        .then((json) => {
          console.log(json);
          alert(
            `Your 404 (Error) Page settings have been updated.  Please re-publish the "${json.data.updateDomain.errorPage.name}" page for it to take effect for new website visitors.`
          );

          window.location.reload();
        });
    } else {
      alert("No Domain Has Been Set For This Campaign");
    }
  }

  makeThisATemplate() {}

  showSlug() {
    this.setState({
      isActive: true,
    });
  }

  hideSlug() {
    this.setState({
      isActive: false,
    });
  }

  changeSlug(slug = false) {
    const filteredSlug = slugify(slug.toString().toLowerCase());

    if (filteredSlug === "") {
      alert(
        "Sorry!  Your Slug Cannot be Empty.  Please Try Again.\n\nIf you want to make this page your Home Page, click Page Actions > This is my Home Page."
      );
    } else {
      this.setState({ slug: filteredSlug });

      this.props.updatePageName({
        variables: {
          pageId: this.props.settings.page.id,
          slug: filteredSlug,
        },
      });
    }
  }

  renameObject(name = false) {
    const newObjectName = name
      ? name
      : window.prompt("Please Rename This Object", this.state.settings.name);

    if (newObjectName) {
      const variables = {
        name: newObjectName,
        deleted: false,
        screenshot: this.state.settings.screenshot,
        id: this.state.settings.id,
        // connectToIds: this.state.settings.connectTo.map(obj => obj.id)
      };

      console.log({ variables });

      // update campaign with newobject name first before saving
      this.setState(
        (prevState) => ({
          settings: {
            ...prevState.settings,
            name: newObjectName,
          },
        }),
        () => {
          this.props
            .updateCampaignObjectMutation({
              variables,
            })
            .then((json) => {
              const pageId = this.props.settings.page.id;
              console.log({ pageId });

              this.props.updatePageName({
                variables: {
                  pageId,
                  name: newObjectName,
                },
              });
            });
        }
      );
    }
  }

  async deleteObject() {
    if (window.confirm("Are you sure you want to delete this page?")) {
      await this.props.removeCanvasObject(this.props.settings.id);
    }
  }

  async cloneObject() {
    const { showCloneObjectPopup, settings } = this.props;
    showCloneObjectPopup(settings);
  }

  render() {
    const { app } = this.context;
    const { getCampaignState, setCampaignState, settings } = this.props;
    const pageId = settings.page ? settings.page.id : false;

    const isHome = _.has(this.props, "settings.page.homePageForDomain.id");
    const isError = _.has(this.props, "settings.page.errorPageForDomain.id");

    if (this.props.getUserQuery.loading || this.state.loading)
      return (
        <div style={{ textAlign: "center" }}>
          <img src={app.loadingImage} alt="Loading..." />
        </div>
      );

    // console.log({ user: this.props.getUserQuery });

    const defaultDomain = `${this.props.getUserQuery.user.subdomain}.${app.domain}`;

    const getComponentFromPlugin = triggerHook(
      "onComponentRender",
      { id: "CanvasObject" },
      settings,
      { getCampaignState, setCampaignState }
    );

    // thumbnail
    const type = this.props.settings.page.type;
    const thumbnailMatches = objects.pages.filter(
      (itm) => itm.pageType === type
    );
    const thumbnail = thumbnailMatches.length
      ? thumbnailMatches[0].screenshot
      : app.logoIcon;

    return (
      <div style={{ padding: "60px 50px" }}>
        <div
          style={{
            marginLeft: 25,
            borderLeft:
              this.props.index < this.props.length ? "1px dashed #CCC" : "none",
            position: "absolute",
            height: 335,
          }}
        />
        <Grid
          onMouseEnter={() => this.setState({ numberActive: true })}
          onMouseLeave={() => this.setState({ numberActive: false })}
        >
          <Cell>
            {this.state.numberActive && (
              <></>
              // <UpDownControls
              //   showUp={this.props.index > 1}
              //   showDown={this.props.index < this.props.length}
              //   id={this.props.settings.id}
              //   useObjects={this.props.useObjects}
              //   updateCampaignObjectMutation={
              //     this.props.updateCampaignObjectMutation
              //   }
              //   setLoading={loading => this.setState({ loading })}
              // />
            )}
            <div
              style={{
                borderRadius: 100,
                padding: !isHome && !isError ? 18 : 12,
                marginRight: 35,
                textAlign: "center",
                width: 50,
                backgroundColor: "white",
                boxShadow: this.state.isActive
                  ? "5px 5px 25px 0 rgba(46,61,73,.35)"
                  : "5px 5px 25px 0 rgba(46,61,73,.2)",
                position: "relative",
              }}
            >
              {isHome ? <FontIcon>home</FontIcon> : null}
              {isError ? <FontIcon>error</FontIcon> : null}
              {!isHome && !isError ? <>{this.props.index}</> : null}
            </div>
          </Cell>
          <Cell
            style={{
              borderRadius: 3,
              backgroundColor: "white",
              boxShadow: this.state.isActive
                ? "5px 5px 25px 0 rgba(46,61,73,.35)"
                : "5px 5px 25px 0 rgba(46,61,73,.2)",
            }}
          >
            <Grid onMouseEnter={this.showSlug} onMouseLeave={this.hideSlug}>
              <Cell style={{ padding: 35, paddingBottom: 0, width: 550 }}>
                <div>
                  <RenamableTitle
                    name={this.state.settings.name}
                    onChange={(name) => this.renameObject(name)}
                    showIcon
                    style={{
                      fontSize: 24,
                      lineHeight: "32px",
                      color: "rgba(0, 0, 0, 0.87)",
                      marginLeft: -7,
                      fontFamily: `'Open Sans', sans-serif`,
                      fontWeight: 300,
                      textAlign: "left",
                    }}
                  />
                  {this.state.slug ? (
                    <div
                      style={{
                        padding: "5px 0",
                        visibility: this.state.isActive ? "visible" : "hidden",
                      }}
                    >
                      <span style={{ fontSize: 12, color: "#999" }}>/</span>
                      <RenamableTitle
                        name={this.state.slug}
                        showIcon
                        onChange={(slug) => this.changeSlug(slug)}
                        style={{
                          fontSize: 12,
                          color: "#999",
                          padding: 0,
                          textAlign: "left",
                        }}
                        iconStyle={{
                          zoom: 0.5,
                          marginLeft: 32,
                          marginTop: -8,
                        }}
                      />
                      <a
                        href={`http://${this.props.domainName ||
                          defaultDomain}/${this.state.slug}`}
                        rel="noopener noreferrer"
                        target="_blank"
                      >
                        <FontIcon
                          style={{
                            zoom: 0.5,
                            marginLeft: 10,
                            position: "relative",
                            top: 3,
                            color: "#666",
                          }}
                        >
                          launch
                        </FontIcon>
                      </a>
                    </div>
                  ) : null}
                </div>
                <Link to={`${pageId}/builder`}>
                  <Button secondary style={{ margin: "25px 0" }}>
                    Edit Page &gt;
                  </Button>
                </Link>

                <div style={style.bigToolbar.innerInfoBar}>
                  <Grid justify="space-between">
                    <Cell />
                    <Cell style={{ padding: 5 }}>
                      <Menu
                        label="Page Actions"
                        style={{
                          width: 220,
                          cursor: "pointer",
                          textAlign: "right",
                        }}
                      >
                        <div>
                          <Link to={`${pageId}/builder`}>
                            <ListItem>Edit Page</ListItem>
                          </Link>
                          <Link
                            target="_blank"
                            to={`${pageId}/builder/preview`}
                          >
                            <ListItem>Preview Page</ListItem>
                          </Link>
                          <ListItem onClick={this.renameObject}>
                            Rename Page
                          </ListItem>
                          <ListItem onClick={this.deleteObject}>
                            Delete Page
                          </ListItem>
                          <div style={style.divider} />
                          <ListItem onClick={this.cloneObject}>
                            Make a Copy
                          </ListItem>
                          <ListItem
                            onClick={() => {
                              const slug = prompt(
                                `What url would you like this page to have?\n\nhttp://${this.props.domainName}/`,
                                this.state.slug
                              );
                              if (slug) this.changeSlug(slug);
                            }}
                          >
                            Change the Page URL/Slug
                          </ListItem>
                          <div style={style.divider} />
                          <ListItem onClick={this.makeThisMyHomePage}>
                            Make This My Home Page
                          </ListItem>
                          <ListItem onClick={this.makeThisMy404Page}>
                            Make This My 404 (Error) Page
                          </ListItem>
                        </div>
                      </Menu>
                    </Cell>
                  </Grid>
                </div>
              </Cell>
              <Cell
                style={{
                  width: 250,
                  backgroundColor: "#EEE",
                  textAlign: "center",
                  backgroundImage: `url(${thumbnail})`,
                  backgroundPosition: "center",
                  backgroundSize: thumbnailMatches.length ? "cover" : "auto",
                  backgroundRepeat: "no-repeat",
                }}
              >
                {getComponentFromPlugin.length
                  ? React.createElement(
                      _.head(getComponentFromPlugin),
                      this.props
                    )
                  : null}
              </Cell>
            </Grid>
          </Cell>
        </Grid>
      </div>
    );
  }
}

export default CampaignLegendObject;
