import { utc, ISO_8601, duration } from "moment";
import React, { Component } from "react";
import { connect } from "react-redux";
import { Redirect } from "react-router-dom";
import {
  Container,
  Header,
  Item,
  Pagination,
  Loader,
  Label
} from "semantic-ui-react";
import {
  getEmployerFromPrice,
  getPriceFromPrice
} from "./ProviderShiftsShared";
import { getPShiftsRequest } from "../../../actions/pShift/saga.actions";

class ProviderShifts 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(
      getPShiftsRequest({
        page: this.state.page,
        page_size: this.state.pageSize
      })
    );
  };

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

  render() {
    const {
      isSendingPShiftRequest,
      pShiftRequestSuccess,
      selfUser
    } = this.props;
    const { page, pageSize } = this.state;
    if (selfUser.provider) {
      return (
        <ProviderShiftsView
          isSendingPShiftRequest={isSendingPShiftRequest}
          pShiftRequestSuccess={pShiftRequestSuccess}
          page={page}
          pageSize={pageSize}
          user={selfUser}
          handlePaginationChange={this.handlePaginationChange}
        />
      );
    } else {
      return <Redirect to="/" />;
    }
  }
}

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

const ProviderShiftsView = ({
  isSendingPShiftRequest,
  pShiftRequestSuccess,
  user,
  page,
  pageSize,
  handlePaginationChange
}) => {
  const { count = 0, results = [] } = pShiftRequestSuccess;
  return (
    <Container>
      <Header>Shifts</Header>
      {!!isSendingPShiftRequest && <Loader content="Loading" />}
      {!isSendingPShiftRequest &&
        results.length > 0 && (
          <Item.Group divided>
            {results.map(result => {
              const employer = getEmployerFromPrice(result.price, user);
              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 displayText = duration(min, "minutes").humanize();
              if (min % 60) {
                displayText = duration(
                  Math.floor(min / 60),
                  "hours"
                ).humanize();
                displayText += ` and ${duration(
                  min % 60,
                  "minutes"
                ).humanize()}`;
              }
              return (
                <Item key={result.uuid}>
                  <Item.Content>
                    <Item.Header>
                      <Label
                        circular
                        empty
                        style={{
                          backgroundColor: workType.color,
                          borderColor: workType.color
                        }}
                      />
                      {workType.label}
                    </Item.Header>
                    <Item.Meta>
                      {"At " +
                        utc(result.set_start, ISO_8601)
                          .local(false)
                          .format("dddd, MMMM Do YYYY, h:mm a Z") +
                        "; for " +
                        displayText +
                        "; rate $" +
                        price.amount +
                        "/hour"}
                    </Item.Meta>
                    <Item.Description>{result.description}</Item.Description>
                    {/* <code>{JSON.stringify(result, null, 2)}</code> */}
                    <Item.Meta>
                      <a href={"mailto:" + employer.client.email}>
                        {employer.client.email}
                      </a>
                    </Item.Meta>
                  </Item.Content>
                </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)(ProviderShifts);
