import React, { useRef } from 'react'
import { useInput, useRegisterKeybindingContext } from '@anthropic/ink'
import {
  loadBuddyData,
  getActiveCreature,
  BattleFlow,
  type BuddyData,
  type BattleFlowHandle,
} from '@claude-code-best/pokemon'
import type { ToolUseContext } from '../../Tool.js'
import type {
  LocalJSXCommandContext,
  LocalJSXCommandOnDone,
} from '../../types/command.js'

async function getOrInitBuddyData(): Promise<BuddyData> {
  let data = await loadBuddyData()
  if (!getActiveCreature(data)) {
    data = await loadBuddyData()
  }
  return data
}

export async function call(
  onDone: LocalJSXCommandOnDone,
  _context: ToolUseContext & LocalJSXCommandContext,
  _args: string,
): Promise<React.ReactNode> {
  const data = await getOrInitBuddyData()

  if (!getActiveCreature(data)) {
    onDone('No companion yet · run /buddy first', { display: 'system' })
    return null
  }

  return React.createElement(BattlePanel, {
    buddyData: data,
    onClose: () => {
      onDone('battle closed', { display: 'system' })
    },
  })
}

function BattlePanel({
  buddyData,
  onClose,
}: {
  buddyData: BuddyData
  onClose: () => void
}) {
  const inputRef = useRef<BattleFlowHandle | null>(null)

  // Register keybinding context so our shortcuts take priority over Global
  useRegisterKeybindingContext('Battle')

  useInput((input, key, event) => {
    // Consume ALL keyboard events to prevent PromptInput from intercepting
    event.stopImmediatePropagation()
    inputRef.current?.handleInput(input, key)
  })

  return React.createElement(BattleFlow, {
    buddyData,
    onClose,
    isActive: true,
    inputRef,
  })
}
