import { PlayIcon, StopIcon, ViewGridAddIcon } from '@heroicons/react/solid'
import React, { useEffect, useState } from 'react'
import type { SubmitHandler } from 'react-hook-form'
import { useForm } from 'react-hook-form'
import 'react-toastify/dist/ReactToastify.css'

import { Hub } from '../../app/providers/Hubs'
import useApiUrlStore from '../../app/store/apiStore'
import { Toast } from '../../components/mollecules'
import type {
  Account,
  Scenario,
  StartBotRequest,
  TradingBot,
} from '../../generated/ManagingApi'
import {
  AccountClient,
  ScenarioClient,
  BotClient,
  BotType,
  Ticker,
  Timeframe,
} from '../../generated/ManagingApi'

import BotList from './botList'
import { useQuery } from '@tanstack/react-query'

const Bots: React.FC = () => {
  const [showModal, setShowModal] = useState(false)
  const { register, handleSubmit } = useForm<StartBotRequest>()
  const { apiUrl } = useApiUrlStore()
  const botClient = new BotClient({}, apiUrl)

  const onSubmit: SubmitHandler<StartBotRequest> = async (form) => {
    closeModal()
    const t = new Toast('Bot is starting')
    await botClient
      .bot_Start(form)
      .then((status: string) => {
        t.update('success', 'Bot status : ' + status)
      })
      .catch((err) => {
        t.update('error', err)
      })
  }

  const { data: bots } = useQuery({
    queryFn: () => botClient.bot_GetActiveBots(),
    queryKey: ['bots'],
  })

  const scenarioClient = new ScenarioClient({}, apiUrl)
  const { data: scenarios } = useQuery({
    queryFn: () => scenarioClient.scenario_GetScenarios(),
    queryKey: ['scenarios'],
  })

  const accountClient = new AccountClient({}, apiUrl)
  const { data: accounts } = useQuery({
    queryFn: () => accountClient.account_GetAccounts(),
    queryKey: ['accounts'],
  })

  // const setupHubConnection = async () => {
  //   const hub = new Hub('bothub', apiUrl).hub

  //   hub.on('BotsSubscription', (bots: TradingBot[]) => {
  //     // eslint-disable-next-line no-console
  //     console.log(
  //       'bot List',
  //       bots.map((bot) => {
  //         return bot.name
  //       })
  //     )
  //     setBots(bots)
  //   })

  //   return hub
  // }

  function openModal() {
    setShowModal(true)
  }

  function closeModal() {
    setShowModal(false)
  }

  async function stopAllBots() {
    const t = new Toast('Stoping all bots')
    await botClient
      .bot_StopAll()
      .then((result) => {
        t.update('success', 'All bots stopped')
      })
      .catch((reason) => {
        t.update('error', reason)
      })
  }

  async function restartAllBots() {
    const t = new Toast('Restarting all bots')
    await botClient
      .bot_RestartAll()
      .then(() => {
        t.update('success', 'All bots restarted')
      })
      .catch((reason) => {
        t.update('error', reason)
      })
  }

  return (
    <div>
      <div className="container mx-auto">
        <div className="tooltip" data-tip="Run new bot">
          <button className="btn btn-primary m-1 text-xs" onClick={openModal}>
            <ViewGridAddIcon width="20"></ViewGridAddIcon>
          </button>
        </div>
        <div className="tooltip" data-tip="Stop all bots">
          <button className="btn btn-error m-1 text-xs" onClick={stopAllBots}>
            <StopIcon width="20"></StopIcon>
          </button>
        </div>
        <div className="tooltip" data-tip="Restart all bots">
          <button
            className="btn btn-success m-1 text-xs"
            onClick={restartAllBots}
          >
            <PlayIcon width="20"></PlayIcon>
          </button>
        </div>
        <BotList list={bots || []} />
        {showModal ? (
          <>
            <div>
              <form onSubmit={handleSubmit(onSubmit)}>
                <div className="modal modal-bottom sm:modal-middle modal-open">
                  <div className="modal-box">
                    <button
                      onClick={closeModal}
                      className="btn btn-sm btn-circle right-2 top-2 absolute"
                    >
                      ✕
                    </button>
                    <div className="text-primary mb-3 text-xl">Run a bot</div>
                    <div className="form-control">
                      <div className="input-group">
                        <label htmlFor="accountName" className="label mr-6">
                          Account
                        </label>
                        <select
                          className="select select-bordered w-full h-auto max-w-xs"
                          {...register('accountName')}
                        >
                          {accounts.map((item) => (
                            <option
                              style={{ color: 'black' }}
                              key={item.name}
                              value={item.name}
                            >
                              {item.name}
                            </option>
                          ))}
                        </select>
                      </div>
                    </div>
                    <div className="form-control">
                      <div className="input-group">
                        <label htmlFor="botName" className="label mr-6">
                          Name
                        </label>
                        <input
                          className="w-full max-w-xs"
                          {...register('botName')}
                        ></input>
                      </div>
                    </div>
                    <div className="form-control">
                      <div className="input-group">
                        <label htmlFor="botType" className="label mr-6">
                          Type
                        </label>
                        <select
                          className="select w-full max-w-xs"
                          {...register('botType')}
                        >
                          {Object.keys(BotType).map((item) => (
                            <option key={item} value={item}>
                              {item}
                            </option>
                          ))}
                        </select>
                      </div>
                    </div>
                    <div className="form-control">
                      <div className="input-group">
                        <label htmlFor="ticker" className="label mr-6">
                          Ticker
                        </label>
                        <select
                          className="select w-full max-w-xs"
                          {...register('ticker')}
                        >
                          {Object.keys(Ticker).map((item) => (
                            <option key={item} value={item}>
                              {item}
                            </option>
                          ))}
                        </select>
                      </div>
                    </div>
                    <div className="form-control">
                      <div className="input-group">
                        <label htmlFor="timeframe" className="label mr-6">
                          Timeframes
                        </label>
                        <select
                          className="select w-full max-w-xs"
                          {...register('timeframe')}
                        >
                          {Object.keys(Timeframe).map((item) => (
                            <option key={item} value={item}>
                              {item}
                            </option>
                          ))}
                        </select>
                      </div>
                    </div>
                    <div className="form-control">
                      <div className="input-group">
                        <label htmlFor="scenario" className="label mr-6">
                          Scenario
                        </label>
                        <select
                          className="select select-bordered w-full h-auto max-w-xs"
                          {...register('scenario')}
                        >
                          {scenarios.map((item) => (
                            <option key={item.name} value={item.name}>
                              {item.name}
                            </option>
                          ))}
                        </select>
                      </div>
                    </div>
                    <div className="form-control">
                      <div className="input-group">
                        <label htmlFor="isForWatchOnly" className="label mr-6">
                          Watch Only
                        </label>
                        <input
                          type="checkbox"
                          {...register('isForWatchOnly')}
                        ></input>
                      </div>
                    </div>
                    <div className="modal-action">
                      <button type="submit" className="btn">
                        Run
                      </button>
                    </div>
                  </div>
                </div>
              </form>
            </div>
          </>
        ) : null}
      </div>
    </div>
  )
}

export default Bots
