import React, { useEffect, useMemo, useState } from 'react'

import { Project } from '@agiliza/api/domain'
import { useFormState } from '@agiliza/utils/hooks/state'
import { ContextButton, DatePicker, PageTitle, SelectField, Table } from '@curio/components'
import { Grid, IconButton } from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles'
import { Publish as PublishIcon, Search as SearchIcon } from '@material-ui/icons'

import { connected, ConnectedProps } from './connect'
import styles from './styles'

interface State {
  beginDate: Date | null
  endDate: Date | null
  statuses: number[]
}

const initState: State = {
  beginDate: null,
  endDate: null,
  statuses: [],
}

const tableColumns = ['ID', 'Número processo', 'Situação', 'Ações']

type ExtendedProps = WithStyles<typeof styles> & ConnectedProps

interface Props extends ExtendedProps {}

const Searcher = (props: Props) => {
  const { classes, searching, submitting, projects, context } = props

  const { state, actions } = useFormState('searcher', initState)

  const { beginDate, endDate, statuses } = state

  const [selectedProjects, setSelectedProjects] = useState<string[]>([])
  const [status, setStatus] = useState('')

  useEffect(() => {
    props.getContext()
  }, [])

  const handleChangeDate = (type: keyof Pick<State, 'beginDate' | 'endDate'>) => (date: Date | null) => {
    actions.update({ [type]: date })
  }

  const handleSearch = () => {
    props.getProjects({
      beginDate,
      endDate,
      statuses: status ? [Number(status)] : [],
    })
  }

  const tableKeys = useMemo(() => {
    const id = (p: Project) => p.id
    const processNumber = (p: Project) => p.processNumber
    const situation = (p: Project) => context.statuses.find((st) => st.id === p.status.id)?.description || ''

    const mapToActions = (p: Project) => (
      <ContextButton
        size="small"
        menuId={`entity-${p.id}-actions`}
        menuItems={[
          {
            label: 'Submeter',
            icon: (
              <PublishIcon
                onClick={() => props.submitProjects({ ids: [p.id], onSuccess: () => props.getProjects({ beginDate, endDate, statuses }) })}
              />
            ),
          },
        ]}
      />
    )

    return [id, processNumber, situation, mapToActions]
  }, [projects])

  const handleRowClick = (prj: Project) => {
    const newSelectedProjects = selectedProjects.indexOf(prj.id) !== -1 ? selectedProjects.filter((p) => p !== prj.id) : [...selectedProjects, prj.id]
    setSelectedProjects(newSelectedProjects)
  }

  // const handleSubmitClick = () => {
  //   props.submitProjects({ ids: selectedProjects, onSuccess: () => props.getProjects({ beginDate, endDate, statuses }) })
  // }

  return (
    <div className={classes.pageContent}>
      <PageTitle title="Buscar projetos" />
      <Grid container spacing={2} className={classes.fieldsContainer}>
        <Grid item xs={3}>
          <DatePicker
            id="begin-date"
            label="Data início"
            value={beginDate}
            onChange={handleChangeDate('beginDate')}
            format="dd/MM/yyyy"
            className={classes.datePicker}
          />
        </Grid>
        <Grid item xs={3}>
          <DatePicker
            id="end-date"
            label="Data fim"
            value={endDate}
            onChange={handleChangeDate('endDate')}
            format="dd/MM/yyyy"
            className={classes.datePicker}
          />
        </Grid>
        <Grid item xs={5}>
          <SelectField
            id="statuses-select-field"
            label="Situação"
            value={status}
            onChange={(vl) => setStatus(vl)}
            items={context.statuses.map((mR) => ({ label: mR.description, value: mR.id }))}
            variant="outlined"
            shrink={false}
          />
        </Grid>
        <Grid item xs={1}>
          <IconButton onClick={handleSearch} className={classes.btnSearch}>
            <SearchIcon />
          </IconButton>
        </Grid>
      </Grid>
      {/* <div className={classes.submitBtnContainer}>
        <ButtonWithProgress fetching={submitting} color="primary" disabled={!selectedProjects.length} onClick={handleSubmitClick}>
          Submeter projetos
        </ButtonWithProgress>
      </div> */}
      <Table<Project>
        size="small"
        columns={tableColumns}
        keys={tableKeys}
        data={projects}
        fetching={searching || submitting}
        // selectedRows={selectedProjects}
        onRowClick={handleRowClick}
      />
    </div>
  )
}

export default connected(withStyles(styles)(Searcher))
