import React, { useState } from 'react'
import type { SubmitHandler } from 'react-hook-form'
import { useForm } from 'react-hook-form'
import {
  Account,
  RiskLevel,
  Ticker,
  TradeDirection,
  TradingClient,
} from '../../../generated/ManagingApi'
import Modal from '../../../components/mollecules/Modal/Modal'
import useApiUrlStore from '../../../app/store/apiStore'
import { FormInput, Toast } from '../../../components/mollecules'
import type { IOpenPositionFormInput } from '../../../global/type'

interface GmxPositionModalProps {
  isOpen: boolean
  onClose: () => void
  account: Account
}

const GmxPositionModal: React.FC<GmxPositionModalProps> = ({
  isOpen,
  onClose,
  account,
}) => {

  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const { apiUrl } = useApiUrlStore()
  const client = new TradingClient({}, apiUrl)
  const [selectedTicker, setSelectedTicker] = useState<Ticker>(Ticker.BTC)
  const [selectedDirection, setSelectedDirection] = useState<TradeDirection>(
    TradeDirection.Long
  )
  const { register, handleSubmit } = useForm<IOpenPositionFormInput>()

  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} ${form.ticker} on ${account.name}`)
    setIsLoading(true)
    setError(null)

    try {
      await client.trading_Trade(
        account.name,
        null, // moneyManagementName - assuming none selected
        form.direction,
        form.ticker,
        form.riskLevel,
        false, // isForPaperTrading - adjust if needed
        form.stopLoss, // Pass stopLoss price to openPrice parameter
        undefined // moneyManagement - not passing the full object
      )
      t.update('success', 'Position opened successfully')
      onClose() // Close modal on success
    } catch (err) {
      const errorMessage =
        err instanceof Error ? err.message : 'An unknown error occurred'
      setError(errorMessage)
      t.update('error', `Error: ${errorMessage}`)
    } finally {
      setIsLoading(false)
    }
  }

  const modalContent = (
    <>
      {isLoading ? (
        <div className="text-center py-4">
          <span className="loading loading-spinner loading-md"></span>
          <p>Opening GMX position...</p>
        </div>
      ) : error ? (
        <div className="alert alert-error mb-4">
          <p>{error}</p>
        </div>
      ) : (
        <>
          <div className="mb-4">
            <p className="mb-2">
              <strong>Account:</strong> {account.name}
            </p>
          </div>

          <form onSubmit={handleSubmit(onSubmit)}>
            <div className="flex flex-wrap gap-4 mb-4">
              <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 w-full">
                <input type="checkbox" />
                <div className="collapse-title text-xs font-medium">
                  Add TP/SL
                </div>
                <div className="collapse-content flex flex-col gap-2">
                  <FormInput label="Stop Loss" htmlFor="stopLoss">
                    <input
                      type="number"
                      step="any"
                      placeholder="Enter SL price (used as openPrice)"
                      className="input input-bordered w-full h-auto max-w-xs"
                      {...register('stopLoss', { valueAsNumber: true })}
                    />
                  </FormInput>
                </div>
              </div>
              <button
                type="submit"
                className="btn btn-primary w-full mt-2"
                disabled={isLoading}
              >
                {isLoading ? (
                  <span className="loading loading-spinner"></span>
                ) : (
                  `${selectedDirection} ${selectedTicker}`
                )}
              </button>
            </div>
          </form>

          <div className="mt-4">
            {/* Optionally keep or adjust info message */}
            {/* <div className="alert alert-info"> */}
            {/*  <p className="text-sm"> */}
            {/*    <strong>Note:</strong> Ensure account has sufficient margin.*/}
            {/*  </p>*/}
            {/* </div> */}
          </div>
        </>
      )}
    </>
  )

  return (
    <Modal
      showModal={isOpen}
      onClose={onClose}
      titleHeader="Open GMX Position"
    >
      {modalContent}
    </Modal>
  )
}

export default GmxPositionModal 