import React from 'react'
import {useForm} from 'react-hook-form'
import * as z from 'zod'
import {BotClient, TradeDirection} from '../../generated/ManagingApi'
import useApiUrlStore from '../../app/store/apiStore'
import Toast from './Toast/Toast'

const schema = z.object({
  direction: z.nativeEnum(TradeDirection),
})

type ManualPositionFormValues = z.infer<typeof schema>

interface ManualPositionModalProps {
  showModal: boolean
  botName: string | null
  onClose: () => void
}

function ManualPositionModal({ showModal, botName, onClose }: ManualPositionModalProps) {
  const { apiUrl } = useApiUrlStore()
  const client = new BotClient({}, apiUrl)
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<ManualPositionFormValues>()

  const onSubmit = async (data: ManualPositionFormValues) => {
    if (!botName) return

    const t = new Toast('Opening position...')
    try {
      await client.bot_OpenPositionManually({
        identifier: botName,
        direction: data.direction,
      })
      t.update('success', 'Position opened successfully')
      reset()
      onClose()
    } catch (error: any) {
      t.update('error', `Failed to open position: ${error.message || error}`)
    }
  }

  if (!showModal || !botName) return null

  return (
    <dialog open={showModal} className="modal modal-bottom sm:modal-middle modal-open">
      <div className="modal-box">
        <h3 className="font-bold text-lg">Open Position Manually for {botName}</h3>
        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="form-control w-full max-w-xs py-2">
            <label className="label">
              <span className="label-text">Direction</span>
            </label>
            <select {...register('direction')} className="select select-bordered w-full max-w-xs">
              <option value={TradeDirection.Long}>Long</option>
              <option value={TradeDirection.Short}>Short</option>
            </select>
            {errors.direction && <span className="text-error text-xs">{errors.direction.message}</span>}
          </div>

          <div className="modal-action">
            <button type="submit" className="btn btn-primary">Open Position</button>
            <button type="button" className="btn" onClick={() => { reset(); onClose(); }}>Cancel</button>
          </div>
        </form>
      </div>
       {/* Click outside closes modal */}
       <form method="dialog" className="modal-backdrop">
          <button type="button" onClick={() => { reset(); onClose(); }}>close</button>
       </form>
    </dialog>
  )
}

export default ManualPositionModal 