import {ColorSwatchIcon, TrashIcon} from '@heroicons/react/solid'
import {useQuery} from '@tanstack/react-query'
import React, {useEffect, useState} from 'react'

import 'react-toastify/dist/ReactToastify.css'
import useApiUrlStore from '../../app/store/apiStore'
import {Loader} from '../../components/atoms'
import {Modal, Toast} from '../../components/mollecules'
import {BacktestModal, BacktestTable} from '../../components/organism'
import type {Backtest} from '../../generated/ManagingApi'
import {BacktestClient} from '../../generated/ManagingApi'

const BacktestScanner: React.FC = () => {
  const [backtestingResult, setBacktest] = useState<Backtest[]>([])
  const [showModal, setShowModal] = useState(false)
  const [showModalRemoveBacktest, setShowModalRemoveBacktest] = useState(false)
  const { apiUrl } = useApiUrlStore()
  const client = new BacktestClient({}, apiUrl)

  const { isLoading, refetch, data: backtests } = useQuery({
    queryFn: () => client.backtest_Backtests(),
    queryKey: ['backtests'],
  })

  useEffect(() => {
    if (backtests) {
      setBacktest(backtests)
    }
  }, [backtests])

  const openModalRemoveBacktests = () => {
    setShowModalRemoveBacktest(true)
  }

  const closeModalRemoveBacktest = () => {
    setShowModalRemoveBacktest(false)
  }

  const onSubmitRemoveBacktest = async (event: any) => {
    event.preventDefault()

    const form = {
      finalPnl: Number(event.target.finalPnl.value),
      hp: Number(event.target.hp.value),
      winRate: Number(event.target.winRate.value),
    }
    const notify = new Toast(`Deleting Backtests...`)
    const client = new BacktestClient({}, apiUrl)
    closeModalRemoveBacktest()

    if (!backtestingResult) {
      return
    }

    const backTestToDelete = backtestingResult.filter((backtest: any) => {
      const H_P = backtest.growthPercentage - backtest.hodlPercentage
      return (
        backtest.winRate <= form.winRate &&
        backtest.finalPnl <= form.finalPnl &&
        H_P <= form.hp
      )
    })
    backTestToDelete.forEach(async (backtest) => {
      return await client
        .backtest_DeleteBacktest(backtest.id)
        .then(() => {})
        .catch((err) => {
          notify.update('error', err)
        })
    })
    notify.update('success', 'Backtest deleted')
  }

  function openModal() {
    setShowModal(true)
  }

  const closeModal = () => {
    setShowModal(false)
  }

  if (isLoading) {
    return <Loader />
  }

  return (
    <div className="container mx-auto">
      <div className="tooltip" data-tip="Run backtest">
        <button className="btn btn-secondary m-1 text-xs" onClick={openModal}>
          <ColorSwatchIcon width="20"></ColorSwatchIcon>
        </button>
      </div>
      <div className="tooltip" data-tip="Delete all Backtests inferior to 50%">
        <button
          className="btn btn-primary m-1 text-xs"
          onClick={openModalRemoveBacktests}
        >
          <TrashIcon width="20"></TrashIcon>
        </button>
      </div>

      <BacktestTable list={backtestingResult} isFetching={isLoading} setBacktests={setBacktest} />

      <BacktestModal
        showModal={showModal}
        closeModal={closeModal}
        setBacktests={setBacktest}
      />

      {/****************************/}
      {/* MODAL TO REMOVE BACKTEST */}
      {/****************************/}
      <Modal
        showModal={showModalRemoveBacktest}
        onSubmit={onSubmitRemoveBacktest}
        onClose={closeModalRemoveBacktest}
        titleHeader={'Remove Backtest'}
      >
        <div className="form-control">
          <div className="input-group">
            <label htmlFor="finalPnl" className="label mr-6">
              PnL{'<'}
            </label>
            <label className="input-group">
              <input
                type="number"
                className="input"
                name="finalPnl"
                defaultValue={0}
              />
            </label>
          </div>
        </div>
        <div className="form-control">
          <div className="input-group">
            <label htmlFor="winRate" className="label mr-6">
              WinRate{'<'}
            </label>
            <label className="input-group">
              <input
                type="number"
                className="input"
                name="winRate"
                defaultValue={50}
              />
            </label>
          </div>
        </div>
        <div className="form-control">
          <div className="input-group">
            <label htmlFor="hp" className="label mr-6">
              H/P{'<'}
            </label>
            <label className="input-group">
              <input
                type="number"
                className="input"
                name="hp"
                defaultValue={3}
              />
            </label>
          </div>
        </div>
        <div className="modal-action">
          <button type="submit" className="btn">
            Run
          </button>
        </div>
      </Modal>
    </div>
  )
}

export default BacktestScanner
