import { ___fillTheForm, ___findDates, ___formatDate, ___ucWords } from '../../helpers'
import Database from '../../controllers/Database'
import { FILTER_GRID_DATA_BY_ROUTE } from '../../redux/reducersTypes'
import Context from '../../redux/context'
import { useContext } from 'react'

const getRaw = e => e.target.closest('.category-row')

const NotesRows = note => {
  const { route, dispatchStorage, setShow } = useContext(Context)

  const toAction = e => {
    const row = getRaw(e)
    const noteID = +(row.dataset.id || -1)
    const noteAction = e.target.dataset.action

    if (noteAction === 'editNote') {

      setShow(true)
      setTimeout(() => {
        ___fillTheForm(document.getElementById('editNoteForm'), Database.getNoteByID(noteID))
      }, 224)

    } else {

      if (typeof Database[noteAction] === 'function') {
        row.classList.add(noteAction)
        setTimeout(() => {
          Database[noteAction](noteID)
          dispatchStorage({ type: FILTER_GRID_DATA_BY_ROUTE, payload: route })
          row.classList.remove(noteAction)
        }, 999)
      }
    }
  }

  return (
    <tr className="category-row" data-id={note.id}>
      <td>{___formatDate(note.createdAt)}<i className={`icon icon-${note.category}`}/></td>
      <td className="uk-text-bold">{note.title}</td>
      <td>{___ucWords(note.category)}</td>
      <td dangerouslySetInnerHTML={{ __html: note.content }}/>
      <td>{___findDates(note.content)}</td>
      <td className="icon icon-edit grid-control" onClick={toAction} data-action="editNote"/>
      <td className={`icon icon-${note.archive === 'on' ? 'un' : ''}archive grid-control`}
          onClick={toAction}
          data-action={(note.archive === 'on' ? 'unA' : 'a') + 'rchiveNote'}/>
      <td className="icon icon-delete grid-control" onClick={toAction} data-action="deleteNote"/>
    </tr>
  )
}

const SummaryRows = (sum) => {
  return (
    <tr className="category-row">
      <td>{___ucWords(sum.title)}<i className={`icon icon-${sum.title}`}/></td>
      <td>{sum.active}</td>
      <td>{sum.archived}</td>
    </tr>
  )
}

const GridViewBody = ({ data, route }) => {
  return (
    <tbody>
    {(() => (route !== 'summary')
        ? data.map((note, key) => <NotesRows key={key + '-' + note.id} {...note} />)
        : data.map((note, key) => <SummaryRows key={key} {...note} />)
    )()}
    </tbody>
  )
}

export default GridViewBody