import _ from "lodash";
import React, { Component } from "react";
import styled from "styled-components";
import { Cell, FontIcon, Grid, ListItem, MenuButton } from "..";

class MultiSelector extends Component {
  constructor(props) {
    super(props);
    this.state = {
      choice: props.choice
    };
    this.toggleSelect = this.toggleSelect.bind(this);
    this.toggleTrial = this.toggleTrial.bind(this);
    this.setStepNum = this.setStepNum.bind(this);
    this.setPic = this.setPic.bind(this);
  }

  toggleSelect(itm) {
    this.setState(
      prevState => {
        // selected choices must be part of passed over items
        const choice = prevState.choice;
        if (choice) {
          const index = choice.findIndex(i => i.id === itm.id);

          if (index > -1) {
            // remove it
            return {
              choice: [...choice.slice(0, index), ...choice.slice(index + 1)]
            };
          }
        }

        // add it
        return {
          choice: [...choice, itm]
        };
      },
      () => this.props.onChange(this.state.choice)
    );
  }

  toggleTrial(itm) {
    const item = this.state.choice.filter(i => i.id === itm.id)[0];
    const newItem = _.has(item, "trial")
      ? _.omit(item, "trial")
      : {
          ...item,
          trial: {
            product_id: item.id
          }
        };

    this.setState(
      prevState => {
        const index = prevState.choice.findIndex(c => c.id === item.id);
        console.log({ index });
        return {
          choice: [
            ...prevState.choice.slice(0, index),
            newItem,
            ...prevState.choice.slice(index + 1)
          ]
        };
      },
      () => this.props.onChange(this.state.choice)
    );
  }

  setStepNum(itm) {
    const item = this.state.choice.filter(i => i.id === itm.id)[0];
    const step_num = window.prompt(
      "Set the Step Number",
      _.has(item, "step_num") ? item.step_num : 0
    );

    if (step_num) {
      this.setState(
        prevState => {
          const choice = prevState.choice;
          const index = choice.findIndex(i => i.id === itm.id);

          const updatedItem =
            step_num === "0" ? _.omit(itm, "step_num") : { ...itm, step_num };

          return {
            choice: [
              ...choice.slice(0, index),
              { ...updatedItem },
              ...choice.slice(index + 1)
            ]
          };
        },
        () => this.props.onChange(this.state.choice)
      );
    }
  }

  setPic(itm) {
    const item = this.state.choice.filter(i => i.id === itm.id)[0];
    const image = window.prompt(
      "Please enter the URL of your image",
      _.get(item, "image", "")
    );

    if (image) {
      this.setState(
        prevState => {
          const choice = prevState.choice;
          const index = choice.findIndex(i => i.id === itm.id);

          const updatedItem = !image ? _.omit(itm, "image") : { ...itm, image };

          return {
            choice: [
              ...choice.slice(0, index),
              { ...updatedItem },
              ...choice.slice(index + 1)
            ]
          };
        },
        () => this.props.onChange(this.state.choice)
      );
    }
  }

  render() {
    const { items, columns } = this.props;
    const { choice } = this.state;

    const CellStyle = styled.div`
      text-align: left;
      border: 1px solid #ccc;
      border-radius: 2px;
      cursor: pointer;
      margin: 5px;
      position: relative;
      &:hover {
        background-color: #eee;
        color: black;
      }
    `;

    return (
      <Grid
        wrap
        justify="stretch"
        style={{ maxHeight: 250 /*, overflowY: "auto" */ }}
      >
        {!items.length ? (
          <div style={{ padding: 30, textAlign: "center", width: "100%" }}>
            No Items Found. Please Try Again
          </div>
        ) : null}
        {items.map(itm => {
          const isSelected = _.find(
            choice,
            i => parseInt(i.id, 10) === parseInt(itm.id, 10)
          );
          const isTrial = _.find(
            choice,
            i =>
              parseInt(i.id, 10) === parseInt(itm.id, 10) && _.has(i, "trial")
          );

          return (
            <Cell
              style={{ width: `${100 / columns}%` }}
              key={itm.id}
              onClick={() => this.toggleSelect(itm)}
            >
              <CellStyle style={{ height: 65 }}>
                <Grid justify="space-between" style={{ padding: 10 }}>
                  <Cell>
                    <FontIcon style={{ marginTop: 0, marginRight: 10 }}>
                      {isSelected ? "check_circle" : "add_circle_outline"}
                    </FontIcon>
                  </Cell>
                  <Cell style={{ width: "100%", textAlign: "left" }}>
                    {itm.name}
                  </Cell>
                  {this.props.showOptions ? (
                    <Cell onClick={e => e.stopPropagation()}>
                      <MenuButton icon="more_vert">
                        <ListItem
                          onClick={() => {
                            this.toggleTrial(itm);
                          }}
                        >
                          {!isTrial
                            ? `Process as a Trial`
                            : `Do not process as a trial`}
                        </ListItem>
                        <ListItem onClick={() => this.setStepNum(itm)}>
                          Set the Funnel 'Step Number'
                        </ListItem>
                        <ListItem onClick={() => this.setPic(itm)}>
                          Set the Product's Picture
                        </ListItem>
                      </MenuButton>
                    </Cell>
                  ) : null}
                </Grid>
              </CellStyle>
            </Cell>
          );
        })}
      </Grid>
    );
  }
}

MultiSelector.defaultProps = {
  columns: 3,
  choice: [],
  items: [],
  showMoreOptions: false,
  onChange: () => false
};

export default MultiSelector;
