import React from 'react';
import Menu from './theme/Menu';
import Settings from './theme/Settings';

import { connect } from 'react-redux';
import { admin as adminApi } from '@devcms/sdk';
import { showSuccess, showError } from '../../../actions/notice';

class ThemeSettings extends React.Component {
  state = {
    settings: {},
    loaded: false
  };

  constructor(props) {
    super(props);

    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
  }

  componentDidMount() {
    adminApi.settings.list({ group: 'theme' })
      .then((settings) => settings.reduce((acc, cur) => {
        acc[cur.name] = cur.value;

        return acc;
      } , {}))
      .then((settings) => this.setState({ settings, loaded: true }))
      .catch((error) => this.props.showError(error));
  }

  handleSubmit(e) {
    e.preventDefault();

    const settings = Object.entries(this.state.settings)
      .map(([name, value]) => ({ name: name, value: value, group: 'theme'}));

    adminApi.settings.import({ settings: settings })
      .then(() => this.props.showSuccess('Saved!'))
      .catch((err) => this.props.showError(err))
  }

  handleInputChange(name, value) {
    this.setState({ settings: { [name]: value } });
  }

  fieldsFor(fields) {
    const keys = Object.keys(fields);

    return Object.keys(this.state.settings)
      .filter(key => keys.includes(key))
      .reduce((obj, key) => {
        obj[key] = this.state.settings[key];

        return obj;
      }, {});
  }

  renderMenus() {
    if (!this.state.loaded) {
      return null;
    }

    return Object.entries(this.props.site.schema.menus).map(([name, info]) => {
      return <Menu
        items={this.state.settings[name]}
        info={info}
        name={name}
        onChange={this.handleInputChange}
        key={`menu-${name}`} />;
    });
  }

  renderSettings() {
    if (!this.state.loaded) {
      return null;
    }

    return Object.entries(this.props.site.schema.settings).map(([name, info]) => {
      return <Settings
        settings={this.fieldsFor(info.fields)}
        info={info}
        onChange={this.handleInputChange}
        key={`settings-${name}`} />;
    });
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <div className="title title-action">
          <button type="submit" className="btn btn-blue">Save</button>
          <div>
            <h1>Theme Settings</h1>
            <p>Here you can set up things like menus and stuff that are related to theme that you use</p>
          </div>
        </div>

        {this.renderMenus()}
        {this.renderSettings()}
      </form>
    );
  }
}

export default connect(
  (state) => ({
    site: state.site
  }),
  { showSuccess, showError }
)(ThemeSettings);
