import React, { Component } from "react";
import { GithubPicker } from "react-color";
import { connect } from "react-redux";
import { Container, Form, Header, Label, Message } from "semantic-ui-react";

import {
  clearWorktypeRequestError,
  clearWorktypeRequestSuccess,
  setFormWorktypeColor,
  setFormWorktypeLabel
} from "../../../actions/worktype/reducer.actions";
import { createWorktypeRequest } from "../../../actions/worktype/saga.actions";
import Error from "../../Shared/Error";

class CreateWorkTypeForm extends Component {
  componentWillUnmount = () => {
    this.props.dispatch(clearWorktypeRequestError());
    this.props.dispatch(clearWorktypeRequestSuccess());
  };

  changeLabel = event => {
    this.props.dispatch(setFormWorktypeLabel(event.target.value));
  };

  changeColor = color => {
    this.props.dispatch(setFormWorktypeColor(color.hex));
  };

  onSubmitWorktype = event => {
    event.preventDefault();
    const { label, color } = this.props;
    this.props.dispatch(createWorktypeRequest({ label, color }));
  };

  render() {
    const {
      isSendingWorktypeRequest,
      worktypeRequestError,
      worktypeRequestSuccess,
      label,
      color
    } = this.props;

    return (
      <CreateWorkTypeFormView
        isSendingWorktypeRequest={isSendingWorktypeRequest}
        worktypeRequestError={worktypeRequestError}
        worktypeRequestSuccess={worktypeRequestSuccess}
        label={label}
        color={color}
        changeLabel={this.changeLabel}
        changeColor={this.changeColor}
        onSubmitWorktype={this.onSubmitWorktype}
      />
    );
  }
}

function mapStateToProps(state) {
  return { ...state.worktype };
}

const CreateWorkTypeFormView = ({
  isSendingWorktypeRequest,
  worktypeRequestError,
  worktypeRequestSuccess,
  label,
  color,
  changeLabel,
  changeColor,
  onSubmitWorktype
}) => (
  <Container>
    <Header>Create Worktype</Header>
    <Form
      loading={isSendingWorktypeRequest}
      onSubmit={onSubmitWorktype}
      error={!!worktypeRequestError}
      success={!!worktypeRequestSuccess}
    >
      <Form.Field>
        <label>Label</label>
        <input
          placeholder="My worktype"
          type="text"
          value={label}
          onChange={changeLabel}
        />
      </Form.Field>
      <Form.Field>
        <label>Color</label>
        <Label
          circular
          empty
          size="massive"
          style={{
            backgroundColor: color,
            borderColor: color
          }}
        />
        <GithubPicker color={color} onChangeComplete={changeColor} />
      </Form.Field>
      <Error header="Create Worktype failed!" error={worktypeRequestError} />
      <Message success>
        <Message.Header>Create Worktype successful!</Message.Header>
        <p>Set worktype successfully.</p>
      </Message>
      <Form.Button>Submit Worktype</Form.Button>
    </Form>
  </Container>
);

export default connect(mapStateToProps)(CreateWorkTypeForm);
