import Pie from "components/graphs/Pie"
import LinkTo from "components/LinkTo"
import { EngagementTrends } from "components/Trends"
import moment from "moment"
import PropTypes from "prop-types"
import React, { useState } from "react"
import { Button, Card } from "react-bootstrap"
import Settings from "settings"
import utils from "utils"

const Kanban = ({ columns, allTasks }) => (
  <div
    style={{
      display: "flex",
      flexDirection: "row",
      overflowX: "auto"
    }}
  >
    {columns.map(column => {
      const name =
        column.name || allTasks.find(task => task.uuid === column)?.shortName
      const tasks =
        (column.tasks &&
          allTasks.filter(task => column.tasks.includes(task.uuid))) ||
        allTasks.filter(task => task.customFieldRef1?.uuid === column)

      return <Column name={name} tasks={tasks} key={name} />
    })}
  </div>
)

Kanban.propTypes = {
  allTasks: PropTypes.array.isRequired,
  // a column is either a UUID of a task with children or a {name, tasks[]} object
  columns: PropTypes.arrayOf(
    PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.shape({
        name: PropTypes.string.isRequired,
        tasks: PropTypes.arrayOf(PropTypes.string).isRequired
      })
    ])
  ).isRequired
}

const Column = ({ name, tasks }) => {
  const [open, setOpen] = useState(false)
  const counters = tasks.reduce((counter, task) => {
    counter[task.customFieldEnum1] = ++counter[task.customFieldEnum1] || 1
    return counter
  }, {})

  return (
    <Card style={{ flex: "1 1 0%", margin: "4px" }}>
      <Card.Header>
        <strong>
          <em>{name} </em>
        </strong>
      </Card.Header>
      <Card.Body>
        <Pie
          width={70}
          height={70}
          data={counters}
          label={`${tasks.length}`}
          segmentFill={entity => {
            const matching = Object.entries(
              Settings.fields.task.customFieldEnum1.enum
            ).filter(([key, val]) => {
              return key === entity.data.key
            })
            return matching.length > 0 ? matching[0][1].color : "#bbbbbb"
          }}
          segmentLabel={d => d.data.value}
        />
        <br />
        <EngagementTrends
          newValue={tasks.reduce(
            (accumulator, task) => accumulator + task.lastMonthReports.length,
            0
          )}
          oldValue={tasks.reduce(
            (accumulator, task) =>
              accumulator + task.preLastMonthReports.length,
            0
          )}
          totalValue={tasks.reduce(
            (accumulator, task) => accumulator + task.allReports.length,
            0
          )}
        />
        <br />
        <br />
        <strong>{Settings.fields.task.longLabel}</strong>
        {"  "}
        <Button
          size="xs"
          onClick={() => setOpen(!open)}
          variant="outline-secondary"
        >
          TRIANGLE TOP OR TRIANGLE BOTTOM ICON
        </Button>
        <br />
        {open && tasks.map(task => <Card task={task} key={task.uuid} />)}
      </Card.Body>
    </Card>
  )
}

Column.propTypes = {
  name: PropTypes.string.isRequired,
  tasks: PropTypes.array.isRequired
}

const CardView = ({ task }) => {
  const [open, setOpen] = useState(false)
  const { customFieldEnum1 } = task
  const enumSettings = Settings.fields.task.customFieldEnum1.enum
  return (
    <Card
      onClick={() => setOpen(!open)}
      style={{
        backgroundColor:
          customFieldEnum1 &&
          (enumSettings[customFieldEnum1]?.color || "#f9f7f7"),
        margin: "3px"
      }}
    >
      <div>
        <LinkTo modelType="Task" model={task}>
          <strong>{task.shortName}</strong>
        </LinkTo>
        <br />
        <EngagementTrends
          newValue={task.lastMonthReports.length}
          oldValue={task.preLastMonthReports.length}
          totalValue={task.allReports.length}
        />
        <br />
        {/* TODO make a single line when collapsed <div style={this.state.open ? {} : {textOverflow: 'ellipsis', whiteSpace: 'nowrap', overflow: 'hidden'}}> */}
        {task.longName && (
          <div>
            <small>
              {open ? task.longName : utils.ellipsize(task.longName, 100)}
            </small>
          </div>
        )}
      </div>

      {open && (
        <Card.Body>
          <small>
            <table cellPadding="4">
              <tbody>
                <tr>
                  <td>created at:</td>
                  <td>
                    {" "}
                    {moment(task.createdAt).format(
                      Settings.dateFormats.forms.withTime
                    )}
                  </td>
                </tr>
                <tr>
                  <td>updated at:</td>
                  <td>
                    {" "}
                    {moment(task.updatedAt).format(
                      Settings.dateFormats.forms.withTime
                    )}
                  </td>
                </tr>
                <tr>
                  <td>tasked organizations:</td>
                  <td>
                    {" "}
                    {this.props.task.taskedOrganizations.map(org => (
                      <LinkTo
                        modelType="Organization"
                        model={org}
                        isLink={false}
                        key={`${org.uuid}`}
                      />
                    ))}
                  </td>
                </tr>
              </tbody>
            </table>
          </small>
        </Card.Body>
      )}
    </Card>
  )
}

CardView.propTypes = {
  task: PropTypes.object.isRequired
}

export default Kanban

@@ -1,16 +1,104 @@
+import %7B Icon %7D from %22@blueprintjs/core%22%0Aimport %7B IconNames %7D from %22@blueprintjs/icons%22%0A
 import Pie from 
@@ -2999,44 +2999,191 @@
     
-TRIANGLE TOP OR TRIANGLE BOTTOM ICON
+%3CIcon%0A            icon=%7B%0A              open%0A                ? IconNames.SYMBOL_TRIANGLE_UP%0A                : IconNames.SYMBOL_TRIANGLE_DOWN%0A            %7D%0A          %3E%0A          %3C/Icon%3E
 %0A   
@@ -3252,16 +3252,20 @@
 =%3E %3CCard
+View
  task=%7Bt

Fix dashboard0