import React, { Component } from "react";
import { connect } from "react-redux";
import { Redirect } from "react-router-dom";
import {
  Container,
  Form,
  Header,
  Input,
  Label,
  Message
} from "semantic-ui-react";
import {
  clearPriceRequestError,
  clearPriceRequestSuccess,
  setFormPriceAmount
} from "../../../actions/price/reducer.actions";
import { updatePriceRequest } from "../../../actions/price/saga.actions";
import Error from "../../Shared/Error";

class UpdatePriceForm extends Component {
  constructor(props) {
    super(props);

    // Get referenced employee
    const { selfUser } = props;
    const employeeUUID = this.props.match.params.providerUUID;
    const employees = ((selfUser || {}).client || {}).employees || [];
    const employee =
      employees.filter(employee => employee.uuid === employeeUUID)[0] || null;

    // Get referenced price
    const priceUUID = this.props.match.params.priceUUID;
    const price =
      (employee.prices || []).filter(
        price => price.uuid === priceUUID && !price.deleted
      )[0] || null;
    this.props.dispatch(setFormPriceAmount((price || {}).amount || ""));
    this.state = {
      price,
      employee
    };
  }

  componentWillMount = () => {
    this.props.dispatch(clearPriceRequestError());
    this.props.dispatch(clearPriceRequestSuccess());
  };

  changeAmount = event => {
    this.props.dispatch(setFormPriceAmount(event.target.value));
  };

  onSubmitPrice = event => {
    event.preventDefault();
    const { amount } = this.props;
    const { price } = this.state;
    this.props.dispatch(
      updatePriceRequest({ uuid: (price || {}).uuid, amount })
    );
  };

  render() {
    const {
      isSendingPriceRequest,
      priceRequestError,
      priceRequestSuccess,
      amount,
      selfUser
    } = this.props;
    const { employee, price } = this.state;

    if (!selfUser.client) {
      return <Redirect to="/" />;
    }

    return (
      <UpdatePriceFormView
        isSendingPriceRequest={isSendingPriceRequest}
        priceRequestError={priceRequestError}
        priceRequestSuccess={priceRequestSuccess}
        employee={employee}
        price={price}
        amount={amount}
        changeAmount={this.changeAmount}
        onSubmitPrice={this.onSubmitPrice}
      />
    );
  }
}

const UpdatePriceFormView = ({
  isSendingPriceRequest,
  priceRequestError,
  priceRequestSuccess,
  employee,
  price,
  amount,
  changeAmount,
  onSubmitPrice
}) => (
  <Container>
    <Header>Update Assigned Work</Header>
    {employee && (
      <Message info>
        <Message.Header>Employee Information</Message.Header>
        <Message.List>
          <Message.Item>UUID: {employee.uuid}</Message.Item>
          <Message.Item>
            Provider Email: {(employee.provider || {}).email || "No Email!"}
          </Message.Item>
          <Message.Item>
            Provider Name:{" "}
            {`${(employee.provider || {}).first_name} ${
              (employee.provider || {}).last_name
            }`.trim() || "No Name!"}
          </Message.Item>
          <Message.Item>
            Provider Phone Number:{" "}
            {`${((employee.provider || {}).userinfo || {}).phone_number ||
              "No Number!"}`}
          </Message.Item>
          <Message.Item>Approved: {"" + employee.approved}</Message.Item>
          <Message.Item>Deleted: {"" + employee.deleted}</Message.Item>
        </Message.List>
      </Message>
    )}
    {!employee && (
      <Message warning>
        <Message.Header>Invalid Employee</Message.Header>
        <p>No accessable employee exists for given UUID.</p>
      </Message>
    )}
    <Form
      loading={isSendingPriceRequest}
      onSubmit={onSubmitPrice}
      error={!!priceRequestError}
      success={!!priceRequestSuccess}
    >
      <Form.Field>
        <label>Work Type</label>
        <span>
          <Label
            circular
            empty
            style={{
              backgroundColor: ((price || {}).work_type || {}).color || "#fff",
              borderColor: ((price || {}).work_type || {}).color || "#fff"
            }}
          />{" "}
          {((price || {}).work_type || {}).label || "Unlabeled"}
          {((price || {}).work_type || {}).deleted && (
            <span>
              {" "}
              <i>(Deleted!)</i>
            </span>
          )}
        </span>
      </Form.Field>
      <Form.Field>
        <label>Hourly Rate</label>
        <Input
          labelPosition="left"
          type=""
          placeholder="Amount"
          onChange={changeAmount}
          value={amount}
        >
          <Label basic>$</Label>
          <input />
        </Input>
      </Form.Field>
      <Error header="Update Price failed!" error={priceRequestError} />
      <Message success>
        <Message.Header>Update Price successful!</Message.Header>
        <p>Price successfully created.</p>
        {!!priceRequestSuccess && (
          <Redirect to="/user/profile/client/providers" />
        )}
      </Message>
      <Form.Button>Update Price</Form.Button>
    </Form>
  </Container>
);

function mapStateToProps(state) {
  return { ...state.price, selfUser: state.user.selfUser };
}

export default connect(mapStateToProps)(UpdatePriceForm);
