import { Tab, Tabs } from "@sc/components/ui";
import _ from "lodash";
import React, { Component } from "react";
import convert from "color-convert";

import {
  ColorPicker,
  DropDownCollapse,
  FancySelector,
  Icon,
  Section,
  UploadGroup,
} from "..";

class Background extends Component {
  constructor(props) {
    super(props);

    this.state = {
      activeTab: props.theActiveTab || "color",
      position: "Automatic",
      repeat: "Don't Repeat",
    };

    this.switchTab = this.switchTab.bind(this);
    this.handleUpload = this.handleUpload.bind(this);
    this.handleColorChange = this.handleColorChange.bind(this);
    this.handlePositionChange = this.handlePositionChange.bind(this);
    this.handleRepeatChange = this.handleRepeatChange.bind(this);
  }

  switchTab(activeTab) {
    this.setState({ activeTab });
  }

  handleUpload(files) {
    const { settings, updateComponentStyle } = this.props;

    console.log("Uploaded Files:", files);

    if (files.length) {
      const file = _.head(files);

      if (!_.has(file, "preview")) {
        Object.assign(file, { preview: URL.createObjectURL(file) });
      }

      updateComponentStyle(
        settings.id,
        {
          backgroundImage: `url(${file.preview})`,
          backgroundPosition: "center center",
          backgroundSize: "cover",
          backgroundRepeat: "no-repeat",
        },
        true,
        false
      );
    }
  }

  handleColorChange(color, dbUpdate = true, scheduleUpdate = false) {
    const { updateComponentStyle, settings } = this.props;

    let rgb = _.get(color, "rgb", this.doColorConversion(color.hex, "rgb"));
    const backgroundColor = `rgb(${rgb.r},${rgb.g},${rgb.b},${rgb.a})`;
    console.log({ backgroundColor });

    updateComponentStyle(
      settings.id,
      {
        backgroundColor,
      },
      dbUpdate,
      scheduleUpdate
    );
  }

  handlePositionChange(position) {
    const { settings, updateComponentStyle } = this.props;

    switch (position) {
      case "auto":
        updateComponentStyle(
          settings.id,
          {
            backgroundPosition: "left",
            backgroundSize: "auto",
            backgroundAttachment: "scroll",
          },
          true,
          false
        );
        this.setState({ position: "Automatic" });
        break;
      case "cover":
        updateComponentStyle(
          settings.id,
          {
            backgroundPosition: "center center",
            backgroundSize: "cover",
            backgroundRepeat: "no-repeat",
          },
          true,
          false
        );
        this.setState({ position: "Cover" });
        break;
      case "contain":
        updateComponentStyle(
          settings.id,
          {
            backgroundPosition: "center center",
            backgroundSize: "contain",
            backgroundRepeat: "no-repeat",
          },
          true,
          false
        );
        this.setState({ position: "Contain" });
        break;
      default:
        break;
    }
  }

  handleRepeatChange(backgroundRepeat) {
    const { settings, updateComponentStyle } = this.props;
    updateComponentStyle(settings.id, { backgroundRepeat }, true, false);

    let repeat = "Don't Repeat";
    if (backgroundRepeat === "repeat-x") repeat = "Left to Right";
    if (backgroundRepeat === "repeat-y") repeat = "Top to Bottom";
    if (backgroundRepeat === "repeat") repeat = "Both (Tile)";
    this.setState({ repeat });
  }

  doColorConversion(colorValue, type = "rgb") {
    if (!colorValue || colorValue === "") return "";

    const extractRgb = (str) => {
      return str
        .replace("rgb(", "")
        .replace(")", "")
        .replace(/ /g, "")
        .split(",");
    };

    // Detect what type of color is coming in a hex color or an rgb
    let sourceType = "keyword";
    if (colorValue.indexOf("#") > -1) sourceType = "hex";
    if (colorValue.indexOf("rgb") > -1) sourceType = "rgb";

    if (type === "rgb") {
      switch (sourceType) {
        case "rgb":
          return {
            r: extractRgb(colorValue)[0],
            g: extractRgb(colorValue)[1],
            b: extractRgb(colorValue)[2],
            a: extractRgb(colorValue)[3] || 1,
          };
        default: {
          const conversion = convert[sourceType].rgb(colorValue);
          if (conversion) {
            return {
              r: conversion[0],
              g: conversion[1],
              b: conversion[2],
              a: conversion[3] || 1,
            };
          } else return false;
        }
      }
    }
  }

  render() {
    const {
      propertiesToHide,
      settings,
      isExpanded,
      label,
      showExtras = true,
      hideTabs = false,
    } = this.props;
    const { activeTab } = this.state;

    let url = "";
    if (settings.hasOwnProperty("properties")) {
      if (settings.properties.hasOwnProperty("backgroundImage")) {
        url = settings.properties.backgroundImage;
        if (url.indexOf("(") > -1)
          url = url.match(/\((.*?)\)/)[1].replace(/('|")/g, "");
      }
    }

    const bgColor = _.get(settings, "properties.backgroundColor", false);
    const bgColorConverted = this.doColorConversion(bgColor, "rgb");

    // console.log({ bgColor, converted: bgColorConverted });

    return (
      <Section
        label={label || "Background"}
        icon="colorize"
        isExpanded={isExpanded}
      >
        {!hideTabs && (
          <Tabs transparent>
            {propertiesToHide.indexOf("color") === -1 ? (
              <Tab
                active={activeTab === "color"}
                onClick={() => this.switchTab("color")}
              >
                Color
              </Tab>
            ) : null}
            {propertiesToHide.indexOf("image") === -1 ? (
              <Tab
                active={activeTab === "image"}
                onClick={() => this.switchTab("image")}
              >
                Image
              </Tab>
            ) : null}
          </Tabs>
        )}

        {activeTab === "color" ? (
          <div style={{ padding: 10 }}>
            <ColorPicker
              {...this.props}
              color={bgColorConverted}
              onChange={this.handleColorChange}
            />
          </div>
        ) : null}

        {activeTab === "image" ? (
          <div label="Image">
            <UploadGroup
              url={url}
              onChange={this.handleUpload}
              highlighted
              hideLabel
            />

            {showExtras &&
            settings.properties.backgroundImage &&
            settings.properties.backgroundImage !== "none" ? (
              <div>
                <DropDownCollapse text={`Position: ${this.state.position}`}>
                  <FancySelector
                    onChange={(id) => this.handlePositionChange(id)}
                    items={[
                      {
                        id: "auto",
                        component: (props) => (
                          <Icon {...props} icon="autorenew" caption="auto" />
                        ),
                      },
                      {
                        id: "cover",
                        component: (props) => (
                          <Icon {...props} icon="burst_mode" caption="cover" />
                        ),
                      },
                      {
                        id: "contain",
                        component: (props) => (
                          <Icon
                            {...props}
                            icon="aspect_ratio"
                            caption="contain"
                          />
                        ),
                      }, //settings_overscan
                    ]}
                  />
                </DropDownCollapse>
                <DropDownCollapse text={`Repeat: ${this.state.repeat}`}>
                  <FancySelector
                    style={{ zoom: 0.85, width: "100%" }}
                    onChange={(id) => this.handleRepeatChange(id)}
                    items={[
                      {
                        id: "no-repeat",
                        component: (props) => (
                          <Icon
                            {...props}
                            icon="block"
                            caption="Don't repeat"
                          />
                        ),
                      },
                      {
                        id: "repeat-x",
                        component: (props) => (
                          <Icon
                            {...props}
                            icon="view_column"
                            caption="Left to Right"
                          />
                        ),
                      },
                      {
                        id: "repeat-y",
                        component: (props) => (
                          <Icon
                            {...props}
                            icon="view_stream"
                            caption="Top to Bottom"
                          />
                        ),
                      },
                      {
                        id: "repeat",
                        component: (props) => (
                          <Icon
                            {...props}
                            icon="view_module"
                            caption="Both (Tile)"
                          />
                        ),
                      },
                    ]}
                  />
                </DropDownCollapse>
              </div>
            ) : null}
          </div>
        ) : null}

        {activeTab === "video" ? (
          <div>
            <UploadGroup text="Video" />
            <DropDownCollapse text="Size: Automatic">
              <FancySelector>
                <Icon icon="settings" caption="auto" />
                <Icon icon="settings" caption="cover" />
                <Icon icon="settings" caption="contain" />
              </FancySelector>
            </DropDownCollapse>
          </div>
        ) : null}
      </Section>
    );
  }
}

Background.propTypes = {};

Background.defaultProps = {
  propertiesToHide: [],
};

export default Background;
