import { utc, ISO_8601, duration } from "moment";
import React, { Component } from "react";
import { connect } from "react-redux";
import { Redirect, Link } from "react-router-dom";
import {
  Button,
  Container,
  Header,
  Item,
  Segment,
  Pagination,
  Popup,
  Loader,
  Label
} from "semantic-ui-react";
import {
  getCShiftsRequest,
  deleteCShiftRequest
} from "../../../actions/cShift/saga.actions";
import { getEmployeeFromPrice, getPriceFromPrice } from "./ClientShiftShared";

class ClientShifts extends Component {
  constructor(props) {
    super(props);
    this.state = {
      page: 1,
      pageSize: 10 // client can't control this, but set here just in case
    };
  }

  componentWillMount = () => {
    this.props.dispatch(
      getCShiftsRequest({
        page: this.state.page,
        page_size: this.state.pageSize
      })
    );
  };

  handlePaginationChange = (event, { activePage }) => {
    this.props.dispatch(
      getCShiftsRequest({
        page: activePage,
        page_size: this.state.pageSize
      })
    );
    this.setState({ page: activePage });
  };

  deleteCShift = uuid => {
    this.props.dispatch(deleteCShiftRequest(uuid));
  };

  render() {
    const {
      isSendingCShiftRequest,
      cShiftRequestSuccess,
      selfUser
    } = this.props;
    const { page, pageSize } = this.state;
    if (selfUser.client) {
      return (
        <ClientShiftsView
          isSendingCShiftRequest={isSendingCShiftRequest}
          cShiftRequestSuccess={cShiftRequestSuccess}
          page={page}
          pageSize={pageSize}
          user={selfUser}
          handlePaginationChange={this.handlePaginationChange}
          deleteCShift={this.deleteCShift}
        />
      );
    } else {
      return <Redirect to="/" />;
    }
  }
}

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

const ClientShiftsView = ({
  isSendingCShiftRequest,
  cShiftRequestSuccess,
  user,
  page,
  pageSize,
  handlePaginationChange,
  deleteCShift
}) => {
  const { count = 0, results = [] } = cShiftRequestSuccess;

  return (
    <Container>
      <Header>Shifts</Header>
      <Segment>
        <Button
          basic
          color="green"
          size="small"
          as={Link}
          to="/user/profile/client/add-shift"
        >
          Schedule a Shift
        </Button>
      </Segment>
      {!!isSendingCShiftRequest && <Loader content="Loading" active />}
      {!isSendingCShiftRequest &&
        results.length > 0 && (
          <Item.Group divided>
            {results.map(result => {
              const employee = getEmployeeFromPrice(result.price, user) || {};
              const provider = employee.provider || {};
              const price = getPriceFromPrice(result.price, user) || {};
              const workType = price.work_type;
              const min = duration(
                utc(result.set_end, ISO_8601) - utc(result.set_start, ISO_8601),
                "milliseconds"
              ).as("minutes");
              let displayDuration = duration(min, "minutes").humanize();
              if (min % 60) {
                displayDuration = duration(
                  Math.floor(min / 60),
                  "hours"
                ).humanize();
                displayDuration += ` and ${duration(
                  min % 60,
                  "minutes"
                ).humanize()}`;
              }
              const approved = !!result.approved;
              const rejected = !result.approved && result.approved !== null;
              const pending = result.approved === null;
              return (
                <Item key={result.uuid}>
                  <Item.Content>
                    <Item.Header>
                      <Label
                        circular
                        empty
                        style={{
                          backgroundColor: workType.color,
                          borderColor: workType.color
                        }}
                      />
                      {workType.label}
                    </Item.Header>
                    <Item.Extra>
                      <Label
                        color={approved ? "green" : rejected ? "red" : "grey"}
                        tag
                        size="small"
                      >
                        {approved && "Approved"}
                        {pending && "Approval Pending"}
                        {rejected && "Rejected"}
                      </Label>
                    </Item.Extra>
                    <Item.Meta>
                      {"At " +
                        utc(result.set_start, ISO_8601)
                          .local(false)
                          .format("dddd, MMMM Do YYYY, h:mm a Z")}
                    </Item.Meta>
                    <Item.Meta>{displayDuration}</Item.Meta>
                    <Item.Meta>{`Rate $${price.amount}/hour`}</Item.Meta>
                    {/* <Item.Description>{result.description}</Item.Description> */}
                    {/* <code>{JSON.stringify(result, null, 2)}</code> */}
                    <Item.Description>
                      {`${provider.first_name} ${provider.last_name}`.trim() ||
                        "No Name!"}{" "}
                      <a href={"mailto:" + provider.email}>{provider.email}</a>
                    </Item.Description>
                  </Item.Content>
                  {result.actual_start === null && (
                    <Item.Extra>
                      <Button
                        primary
                        floated="right"
                        as={Link}
                        to={`/user/profile/client/edit-shift/${result.uuid}`}
                      >
                        Edit
                      </Button>
                      <Popup
                        content={
                          <div>
                            Are you sure you want to delete this shift?<br />
                            <Button
                              basic
                              color="red"
                              size="small"
                              onClick={() => deleteCShift(result.uuid)}
                            >
                              Confirm Deletion
                            </Button>
                          </div>
                        }
                        trigger={
                          <Button color="red" floated="right">
                            Delete
                          </Button>
                        }
                        on="click"
                        position="top right"
                      />
                    </Item.Extra>
                  )}
                </Item>
              );
            })}
          </Item.Group>
        )}
      <div style={{ textAlign: "center" }}>
        <Pagination
          activePage={page}
          onPageChange={handlePaginationChange}
          totalPages={Math.ceil(count / pageSize)}
          boundaryRange={1}
          siblingRange={1}
          size="mini"
          firstItem={undefined}
          lastItem={undefined}
          prevItem={null}
          nextItem={null}
        />
      </div>
    </Container>
  );
};

export default connect(mapStateToProps)(ClientShifts);
