import {TrashIcon} from '@heroicons/react/solid'
import React, {useEffect, useState} from 'react'

import useApiUrlStore from '../../app/store/apiStore'
import {SelectColumnFilter, Table, Toast} from '../../components/mollecules'
import type {IndicatorViewModel} from '../../generated/ManagingApi'
import {ScenarioClient} from '../../generated/ManagingApi'

interface IIndicatorList {
  list: IndicatorViewModel[]
}

const IndicatorTable: React.FC<IIndicatorList> = ({ list }) => {
  const [rows, setRows] = useState<IndicatorViewModel[]>([])
  const { apiUrl } = useApiUrlStore()

  async function deleteIndicator(name: string) {
    const t = new Toast('Deleting indicator')
    const client = new ScenarioClient({}, apiUrl)

    await client
      .scenario_DeleteIndicator(name)
      .then(() => {
        t.update('info', 'Indicator deleted')
      })
      .catch((err) => {
        t.update('error', err)
      })
  }

  const columns = React.useMemo(
    () => [
      {
        Header: 'Name',
        accessor: 'name',
        disableFilters: true,
      },
      {
        Filter: SelectColumnFilter,
        Header: 'Type',
        accessor: 'type',
        disableSortBy: true,
      },
      {
        Filter: SelectColumnFilter,
        Header: 'Signal',
        accessor: 'signalType',
        disableSortBy: true,
      },
      {
        Filter: SelectColumnFilter,
        Header: 'Period',
        accessor: 'period',
        disableSortBy: true,
      },
      {
        Cell: ({ cell }: any) => (
          <>
            <div className="tooltip" data-tip="Delete indicator">
              <button
                data-value={cell.row.values.name}
                onClick={() => deleteIndicator(cell.row.values.name)}
              >
                <TrashIcon className="text-accent w-4"></TrashIcon>
              </button>
            </div>
          </>
        ),
        Header: '',
        accessor: 'id',
        disableFilters: true,
      },
    ],
    []
  )

  useEffect(() => {
    setRows(list)
  }, [list])

  return (
    <div className="flex flex-wrap">
      <Table columns={columns} data={rows} showPagination={true} />
    </div>
  )
}

export default IndicatorTable
