import { useState, useEffect } from 'react'
import type { SubmitHandler } from 'react-hook-form'
import { useForm } from 'react-hook-form'

import { useAuthStore } from '../../../app/store/accountStore'
import useApiUrlStore from '../../../app/store/apiStore'
import { FormInput, GridTile, Toast } from '../../../components/mollecules'
import {
  RiskLevel,
  Ticker,
  TradeDirection,
  TradingClient,
} from '../../../generated/ManagingApi'
import type { IOpenPositionFormInput } from '../../../global/type'

const OpenPositonWidget = () => {
  const { apiUrl } = useApiUrlStore()
  const client = new TradingClient({}, apiUrl)
  const accounts = useAuthStore((state) => state.accounts)
  const [selectedAccount, setSelectedAccount] = useState<string>()
  const [selectedTicker, setSelectedTicker] = useState<Ticker>(Ticker.BTC)
  const [selectedDirection, setSelectedDirection] = useState<TradeDirection>(
    TradeDirection.Long
  )
  const { register, handleSubmit } = useForm<IOpenPositionFormInput>()

  function setSelectedAccountEvent(e: React.ChangeEvent<HTMLInputElement>) {
    setSelectedAccount(e.target.value)
  }

  function setSelectedDirectionEvent(e: React.ChangeEvent<HTMLInputElement>) {
    setSelectedDirection(e.target.value as TradeDirection)
  }

  function setSelectedTickerEvent(e: React.ChangeEvent<HTMLInputElement>) {
    setSelectedTicker(e.target.value as Ticker)
  }

  const onSubmit: SubmitHandler<IOpenPositionFormInput> = async (form) => {
    const t = new Toast(`Opening  ${form.direction} on ${form.ticker}`)
    await client
      .trading_Trade(
        selectedAccount,
        '',
        form.direction,
        form.ticker as Ticker,
        form.riskLevel,
        false,
        form.stopLoss,
        undefined
      )
      .then((result) => {
        t.update('success', 'Position created')
      })
      .catch((err) => {
        t.update('error', 'Error :' + err.message)
      })
  }

  useEffect(() => {
    if (accounts.length !== 0) {
      setSelectedAccount(accounts[0].name)
    }
  }, [accounts])

  return (
    <>
      <GridTile title={'Trade'}>
        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="flex flex-wrap">
            <FormInput label="Account" htmlFor="accountName">
              <select
                className="select select-bordered w-full h-auto max-w-xs"
                {...register('accountName', {
                  onChange(e) {
                    setSelectedAccountEvent(e)
                  },
                })}
              >
                {accounts.map((item) => (
                  <option key={item.name} value={item.name}>
                    {item.name}
                  </option>
                ))}
              </select>
            </FormInput>
            <FormInput label="Direction" htmlFor="direction">
              <select
                className="select select-bordered w-full h-auto max-w-xs"
                {...register('direction', {
                  onChange(e) {
                    setSelectedDirectionEvent(e)
                  },
                  value: selectedDirection,
                })}
              >
                {Object.keys(TradeDirection).map((item) => (
                  <option key={item} value={item}>
                    {item}
                  </option>
                ))}
              </select>
            </FormInput>
            <FormInput label="Ticker" htmlFor="ticker">
              <select
                className="select select-bordered w-full h-auto max-w-xs"
                {...register('ticker', {
                  onChange(e) {
                    setSelectedTickerEvent(e)
                  },
                  value: selectedTicker,
                })}
              >
                {Object.keys(Ticker).map((item) => (
                  <option key={item} value={item}>
                    {item}
                  </option>
                ))}
              </select>
            </FormInput>
            <FormInput label="Risk" htmlFor="riskLevel">
              <select
                className="select select-bordered w-full h-auto max-w-xs"
                {...register('riskLevel')}
              >
                {Object.keys(RiskLevel).map((item) => (
                  <option key={item} value={item}>
                    {item}
                  </option>
                ))}
              </select>
            </FormInput>
            <div className="collapse bg-base-200">
              <input type="checkbox" />
              <div className="collapse-title text-xs font-medium">
                Add TP/SL
              </div>
              <div className="collapse-content">
                <FormInput label="Stop Loss" htmlFor="stopLoss">
                  <input
                    className="w-full h-auto max-w-xs"
                    {...register('stopLoss')}
                  ></input>
                </FormInput>
                <FormInput label="Take Profit" htmlFor="takeProfit">
                  <input
                    className="w-full h-auto max-w-xs"
                    {...register('takeProfit')}
                  ></input>
                </FormInput>
              </div>
            </div>
            <button type="submit" className="btn w-full">
              {selectedDirection} {selectedTicker}
            </button>
          </div>
        </form>
      </GridTile>
    </>
  )
}

export default OpenPositonWidget
