import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import _ from 'lodash/fp'
import {connect} from 'react-redux'
import {createFunction} from './utils'


const getViewComponent = async (view) => {

  const editorModule = require('../weblium-editor.js').default
  const requireInjector = (path) => {
    if (path === 'weblium/editor') {
      return editorModule
    }

    console.log(path)
    throw new Error(`Invalid required path ${path}`)
  }
  const exports = {}
  delete require.cache[require.resolve('iso-morphic-style-loader-jeseeq/lib/addUniversalStyles.js')]
  delete require.cache[require.resolve('css-loader/lib/css-base.js')]
  const styleLoader = require('iso-morphic-style-loader-jeseeq/lib/addUniversalStyles')
  const cssLoader = require('css-loader/lib/css-base.js')
  try {
    createFunction(view)(requireInjector, exports, {
      React,
      PropTypes,
      _,
      classNames,
      styleLoader,
      cssLoader,
    })
  } catch (error) {
    console.log(error)
    return exports.default = (props) => <div>{'' + error}</div>
  }

  return editorModule.viewEnhancer(exports.default)
}

class Preview extends React.Component {
  state = {
    loading: true,
  }

  getView = ({view}) => {
    getViewComponent(view).then((ViewComponent) => {
      if(ViewComponent) {
        this.ViewComponent = ViewComponent
        this.setState({loading: false})
      }
    })
  }

  componentWillMount(){
    const {view} = this.props
    this.getView({view})
  }
  componentDidCatch(error) {
    this.setState({hasError: true, error})
  }

  componentWillReceiveProps({view}){
    if(view !== this.props.view) {
      this.getView({view})
      const oldCss = document.querySelector('[data-preview="preview"]')
      oldCss && oldCss.remove()
    }
  }

  render() {
    const {ViewComponent} = this
    const {resources, initial} = this.props
    const {loading, error, hasError} = this.state
    if (loading) {
      return 'loading'
    }
    if (hasError) {
      return <div>{'' + error}</div>
    }
    const content = ViewComponent.defaultContent || {}
    const theme = content.theme || 'light'
    const $block = {
      id: 'foobar',
      getComponentTheme: () => ({}),
      theme,
      getTheme: () => theme,
      getUrlByRef: (ref, options) => _.get([ref, 'optimized'])(resources),
      inSiteRender: true,
      getErrorComponent: (error) => (props) => <div>{'' + error}</div>
    }
    const uiKitClassName = `ui-kit-${theme}`
    return (
      loading
        ? 'Loading'
        : <div className={classNames({[uiKitClassName]: !initial})}>
            <ViewComponent $block={$block} content={content} />
          </div>
    )
  }
}
export default connect(_.pick(['resources']))(Preview)
