import {connect} from "react-redux"
import React, {Fragment} from "react"
import Collapse from "rc-collapse"
const {Panel} = Collapse
import {CHANGE_UIKIT} from "../actions"
import {Select} from "../components/select"
import $editor from "weblium/editor"
import sandboxData from "weblium/sandbox-data.json"

import {fetchUikit} from "../app"

import "rc-collapse/assets/index.css"

const colorRegex = /(#([0-9a-f]{3}){1,2}|(rgba|hsla)\(\d{1,3}%?(,\s?\d{1,3}%?){2},\s?(1|0?\.\d+)\)|(rgb|hsl)\(\d{1,3}%?(,\s?\d{1,3}%?\)){2})/i
const ButtonComponent = $editor.components.Button

const flattenWithPath = (obj, parentKey = '') => (
  _.flow(
    _.entries,
    _.reduce((acc, [key, value]) => {
      const withPath = _.isEmpty(parentKey) ? key : `${parentKey}-${key}`
      return _.assign(_.isPlainObject(value)
                      ? flattenWithPath(value, withPath)
                      : {[withPath]: value})(acc)
    })({}),
  )(obj)
)

const addUIKitPrefix = (key) => `--ui-${key}`

class Settings extends React.Component {
  state = {}

  changeUiKit = async (id) => {
    const {dispatch} = this.props
    const data = await fetchUikit(id)
    dispatch({type: CHANGE_UIKIT, id, data})
  }

  toggleOverlay = () => this.setState(({overlay}) => ({overlay: !overlay}))

  getStyleAccrodion = (key, value) => {
    const variable = _.pipe(
      _.kebabCase,
      addUIKitPrefix,
    )(key)
    if (_.isString(value) || _.isNumber(value)) {
      if ((`` + value).match(colorRegex)) {
        return (
          <div>
            <span style={{fontWeight: `bold`}}>{`${variable} `}</span>
            <span style={{backgroundColor: value}}>{value}</span>
          </div>
        )
      }
      return (
        <div>
          <span style={{fontWeight: `bold`}}>{`${variable} `}</span>
          <span>{value}</span>
        </div>
      )
    }
    if (_.isArray(value)) {
      const variable = _.pipe(
        _.kebabCase,
        addUIKitPrefix,
      )(key)
      const children = _.map((v) => {
        if ((`` + v).match(colorRegex)) {
          return (
            <div>
              <span style={{fontWeight: `bold`}}>{`${variable} `}</span>
              <span style={{backgroundColor: v}}>{v}</span>
            </div>
          )
        } else {
          return (
            <div>
              <span style={{fontWeight: `bold`}}>{`${variable} `}</span>
              <span>{value}</span>
            </div>
          )
        }
      })(value)
      return (
        <Collapse>
          <Panel header={key}>
            {children}
          </Panel>
        </Collapse>
      )
    }
    return (
      <Collapse>
        <Panel header={key}>
          {_.pipe(_.entries, _.map(([key, value]) => this.getStyleAccrodion(key, value)))(value)}
        </Panel>
      </Collapse>
    )
  }

  getTree = () => {
    const {uiKit} = this.props
    const {typography, palette, button} = uiKit
    const {Background} = $editor.components
    return [
      <Collapse key="colors">
        {_.pipe(
          _.entries,
          _.map(([key, value]) => this.getStyleAccrodion(key, value)))({colors: palette})
        }
      </Collapse>,
      <Collapse key="typography">
        {_.pipe(
          _.entries,
          _.map(([key, value]) => [key, flattenWithPath(value, key)]),
          _.map(([key, value]) => this.getStyleAccrodion(key, value)),
        )(typography)}
      </Collapse>,
      <Collapse key="buttons" className="button-margin">
        <Panel header="buttons">
          {_.flow(
            _.keys,
            _.map((buttonType) => {
            const type = _.kebabCase(buttonType)
            return [<ButtonComponent value={{size: 'md', textValue: type, type}} preventSettings />, <br/>]
            }))(button.types)
          }
        </Panel>
      </Collapse>,
       <Collapse key="dark_buttons">
         <Panel header="dark_buttons" className="no-padding button-margin">
           <Background value={{type: 'color', color: 'black'}}>
             <Fragment>
              {_.flow(
                _.keys,
                _.map((buttonType) => {
                  const type = _.kebabCase(buttonType)
                  return [<ButtonComponent value={{size: 'md', textValue: type, type}}/>, <br/>]
                }))(button.types)
              }
            </Fragment>
          </Background>
        </Panel>
      </Collapse>
    ]
  }

  render() {
    const {overlay} = this.state
    const {uiKit} = this.props
    const options = _.map((id) => ({
      id,
      value: id,
      title: id,
    }))(_.keys(sandboxData.uikitsList))
    return (
      <div className="overlay">
        <button className="button" onClick={this.toggleOverlay}>UIkit</button>
        {overlay && (
          <div>
            Change ui kit
            <Select value={uiKit.id} options={options} id="uikit" onChange={this.changeUiKit} />
            <div>{this.getTree()}</div>
          </div>
        )}
      </div>
    )
  }
}

export default connect(_.pick([`rawUiKits`, `uiKit`]))(Settings)
