import React, { useState } from 'react'
import {
  SortableContainer,
  SortableElement,
  SortableHandle
} from 'react-sortable-hoc'
import arrayMove from 'array-move'

const DragHandle = SortableHandle(() => (
  <div className='listitem-drag-handle'>
    <style jsx>{`
      div {
        width: 20px;
        height: 15px;
        user-select: none;
        cursor: row-resize;
        align-items: center;
        background: linear-gradient(
          top,
          #0006,
          #0006 20%,
          #fff0 0,
          #fff0 40%,
          #0006 0,
          #0006 60%,
          #fff0 0,
          #fff0 80%,
          #0006 0,
          #0006
        );
        background: -webkit-linear-gradient(
          top,
          #0006,
          #0006 20%,
          #fff0 0,
          #fff0 40%,
          #0006 0,
          #0006 60%,
          #fff0 0,
          #fff0 80%,
          #0006 0,
          #0006
        );
      }
    `}</style>
  </div>
))

const SortableItem = SortableElement(({ item }: any) => (
  <li>
    <DragHandle />
    <div className='listitem-content'>{item}</div>

    <style jsx>{`
      li {
        display: grid;
        grid-template-columns: 30px 1fr;
      }
    `}</style>
  </li>
))

const SortableList = SortableContainer(({ items }: { items: any[] }) => {
  return (
    <ul>
      {items.map((item: any, index: number) => {
        return <SortableItem key={item.key} index={index} item={item} />
      })}
      <style jsx>{`
        ul {
          padding: 0;
        }
      `}</style>
    </ul>
  )
})

const SortableComponent = ({ items }: { items: any[] }) => {
  const [state, setState] = useState(items)

  function onSortEnd({
    oldIndex,
    newIndex
  }: {
    oldIndex: number
    newIndex: number
  }) {
    const a = arrayMove(state, oldIndex, newIndex)
    setState(a)
  }
  return (
    <SortableList
      onSortEnd={onSortEnd}
      items={state}
      lockAxis='y'
      useDragHandle={true}
    />
  )
}

export default SortableList
