import {PencilAltIcon, 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 {MoneyManagement} from '../../../generated/ManagingApi'
import {MoneyManagementClient} from '../../../generated/ManagingApi'
import type {IMoneyManagementList} from '../../../global/type'

import MoneyManagementModal from './moneyManagementModal'

const MoneyManagementTable: React.FC<IMoneyManagementList> = ({ list }) => {
  const [rows, setRows] = useState<MoneyManagement[]>([])
  const [showModal, setShowModal] = useState(false)
  const [selectedRow, setSelectedRow] = useState<MoneyManagement>()
  const { apiUrl } = useApiUrlStore()

  async function deleteMoneyManagement(name: string) {
    const t = new Toast('Deleting money management')
    const client = new MoneyManagementClient({}, apiUrl)

    await client
      .moneyManagement_DeleteMoneyManagement(name)
      .then(() => {
        t.update('success', 'Configuration deleted')
      })
      .catch((err) => {
        t.update('error', 'Error :' + err)
      })
  }

  function toggleModal() {
    setShowModal(!showModal)
  }

  function openModal(mm: MoneyManagement) {
    setSelectedRow(mm)
    setShowModal(true)
  }

  const columns = React.useMemo(
    () => [
      {
        Header: 'Name',
        accessor: 'name',
        disableSortBy: true,
      },
      {
        Filter: SelectColumnFilter,
        Header: 'Timeframe',
        accessor: 'timeframe',
        disableSortBy: true,
      },
      {
        Cell: ({ cell }: any) => <>x{cell.row.values.leverage}</>,
        Header: 'Leverage',
        accessor: 'leverage',
        disableFilters: true,
        disableSortBy: true,
      },
      {
        Cell: ({ cell }: any) => <>{cell.row.values.stopLoss * 100} %</>,
        Header: 'SL',
        accessor: 'stopLoss',
        disableFilters: true,
      },
      {
        Cell: ({ cell }) => <>{cell.row.values.takeProfit * 100} %</>,
        Header: 'TP',
        accessor: 'takeProfit',
        disableFilters: true,
      },
      {
        Cell: ({ cell }) => (
          <>
            {(cell.row.values.takeProfit / cell.row.values.stopLoss).toFixed(2)}
          </>
        ),
        Header: 'R/R',
        accessor: 'riskReward',
        disableFilters: true,
      },
      {
        Cell: ({ cell }) => (
          <>
            <div className="tooltip" data-tip="Delete configuration">
              <button
                data-value={cell.row.values.timeframe}
                onClick={() => deleteMoneyManagement(cell.row.values.name)}
              >
                <TrashIcon className="text-accent w-4"></TrashIcon>
              </button>
            </div>
            <div className="tooltip" data-tip="Edit configuration">
              <button
                data-value={cell.row.values.timeframe}
                onClick={() => openModal(cell.row.values)}
              >
                <PencilAltIcon className="text-primary w-4"></PencilAltIcon>
              </button>
            </div>
          </>
        ),
        Header: 'Actions',
        accessor: 'id',
        disableFilters: true,
      },
    ],
    []
  )

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

  return (
    <div className="flex flex-wrap">
      <Table columns={columns} data={rows} />
      <MoneyManagementModal
        showModal={showModal}
        onClose={toggleModal}
        moneyManagement={selectedRow}
      />
    </div>
  )
}

export default MoneyManagementTable
