import { get } from "lodash";
import React, { Component } from "react";
import { getResponsiveSettings, sendData } from "./scripts";
import { WebComponent } from "@sc/modules/page/Builder/WebComponent";
import { triggerHook } from "@sc/plugins/gatsby";

import { PageScripts } from "./addons";
import { CSS } from "./addons";
import { HiddenFields } from "./addons";
import { SEO } from "./addons";
import { ExitIntent } from "./addons";
import { Stats } from "./addons";

var wdt = 0;

class Page extends Component {
  constructor(props) {
    super(props);
    this.state = {
      content: JSON.parse(unescape(get(props, "content", "[]"))),
      currentMobileState: { type: "desktop" },
    };

    this.resize = this.resize.bind(this);
    this.generatePage = this.generatePage.bind(this);
    this.updateComponentSettings = this.updateComponentSettings.bind(this);
    this.updateComponentStyle = this.updateComponentStyle.bind(this);
    this.getComponentSettings = this.getComponentSettings.bind(this);
  }

  componentDidMount() {
    if (typeof window !== "undefined") {
      window.addEventListener("resize", this.resize);
      this.resize();
    }
  }

  componentWillUnmount() {
    if (typeof window !== "undefined") {
      window.removeEventListener("resize", this.resize);
    }
  }

  resize() {
    if (typeof window !== "undefined") {
      const d = document,
        documentElement = d.documentElement,
        body = d.getElementsByTagName("body")[0],
        width = documentElement.clientWidth || body.clientWidth;

      if (width !== wdt) {
        wdt = width;

        if (width >= 1400)
          this.setState({ currentMobileState: { type: "fullscreen" } });
        if (width >= 1000 && width < 1400)
          this.setState({ currentMobileState: { type: "desktop" } });
        if (width >= 768 && width < 1000)
          this.setState({ currentMobileState: { type: "tablet" } });
        if (width < 768)
          this.setState({ currentMobileState: { type: "smartphone" } });
      }
    }
  }

  updateComponentStyle(id, newStyle, callbackFn = () => false) {
    const { content } = this.state;

    const key = content.findIndex((itm) => itm.id === id);
    const settings = content[key];

    const updatedSettings = {
      ...settings,
      properties: {
        ...settings.properties,
        ...newStyle,
      },
    };

    this.updateComponentSettings(id, updatedSettings, callbackFn);
  }

  updateComponentSettings(id, settings, callbackFn = () => false) {
    const { content } = this.state;
    const key = content.findIndex((itm) => itm.id === id);

    this.setState(
      {
        content: [
          ...content.slice(0, key),
          settings,
          ...content.slice(key + 1),
        ],
      },
      callbackFn
    );
  }

  getComponentSettings(id) {
    const { content } = this.state;
    const key = content.findIndex((itm) => itm.id === id);
    return content[key];
  }

  generatePage(content = [], parent = false) {
    const { currentMobileState } = this.state;
    const node = [];
    let i = 0;
    content
      .filter((c) => c.parent === parent)
      .forEach((c) => {
        i += 1;
        const props = {
          settings: getResponsiveSettings(c, currentMobileState),
          // key: Math.random(),
          // key: ++ndct,
          key: c.id,
          sendData,
          updateComponentSettings: this.updateComponentSettings,
          updateComponentStyle: this.updateComponentStyle,
          getComponentSettings: this.getComponentSettings,
          pageContent: this.state.content,
        };

        const internal = c.html || this.generatePage(content, c.id);
        node[i] = (
          <WebComponent
            {...props}
            type={c.type}
            getMobileState={() => currentMobileState}
            mode="live"
            triggerHook={triggerHook}
          >
            {internal}
          </WebComponent>
        );
      });

    return node;
  }

  render() {
    const {
      nextPage = "",
      seoPayload = {},
      merchantPayload = {},
      trackingPayload = {},
      emailPayload = {},
      cssPayload = "",
      exitPayload = {},
      id,
    } = this.props;

    return (
      <>
        <CSS cssPayload={cssPayload} />
        <ExitIntent
          exitPayload={exitPayload}
          getComponentSettings={this.getComponentSettings}
          updateComponentSettings={this.updateComponentSettings}
        />
        <SEO seoPayload={seoPayload} />
        <PageScripts trackingPayload={trackingPayload} />
        {this.generatePage(this.state.content)}
        <HiddenFields
          nextPage={nextPage}
          emailPayload={emailPayload}
          merchantPayload={merchantPayload}
        />
        <Stats pageId={id} />
      </>
    );
  }
}

export { Page };
export default Page;
