import React, { useState } from 'react'
import type { TradeOffer } from '../../types'
import { useInventoryContext } from '../../context/InventoryContext'
import { useScale } from '../../context/ScaleContext'
import { ItemCanvas } from '../ItemCanvas'
import { Tooltip } from '../Tooltip'

interface TradeRowProps {
  trade: TradeOffer
  index: number
  selected: boolean
  onSelect(): void
}

function TradeRow({ trade, index, selected, onSelect }: TradeRowProps) {
  const { scale } = useScale()
  const { sendAction } = useInventoryContext()
  const [hoveredItem, setHoveredItem] = useState<'in1' | 'in2' | 'out' | null>(null)
  const slotSize = 16 * scale

  const handleClick = () => {
    onSelect()
    sendAction({ type: 'trade', tradeIndex: index })
  }

  return (
    <div
      onClick={handleClick}
      style={{
        display: 'flex',
        alignItems: 'center',
        gap: scale * 2,
        padding: `${scale * 2}px`,
        background: selected ? '#555555' : trade.disabled ? '#222222' : '#404040',
        border: `${scale}px solid ${selected ? '#aaaaaa' : '#666666'}`,
        cursor: trade.disabled ? 'not-allowed' : 'pointer',
        opacity: trade.disabled ? 0.6 : 1,
        width: '100%',
        boxSizing: 'border-box',
      }}
    >
      {/* Input 1 */}
      <div
        style={{ position: 'relative' }}
        onMouseEnter={() => setHoveredItem('in1')}
        onMouseLeave={() => setHoveredItem(null)}
      >
        <ItemCanvas item={trade.inputItem1} size={slotSize} />
        {hoveredItem === 'in1' && (
          <Tooltip item={trade.inputItem1} visible />
        )}
      </div>

      {/* Input 2 */}
      {trade.inputItem2 && (
        <div
          style={{ position: 'relative' }}
          onMouseEnter={() => setHoveredItem('in2')}
          onMouseLeave={() => setHoveredItem(null)}
        >
          <ItemCanvas item={trade.inputItem2} size={slotSize} />
          {hoveredItem === 'in2' && (
            <Tooltip item={trade.inputItem2} visible />
          )}
        </div>
      )}

      {/* Arrow */}
      <div style={{ color: '#aaaaaa', fontSize: scale * 8 }}>→</div>

      {/* Output */}
      <div
        style={{ position: 'relative' }}
        onMouseEnter={() => setHoveredItem('out')}
        onMouseLeave={() => setHoveredItem(null)}
      >
        <ItemCanvas item={trade.outputItem} size={slotSize} />
        {hoveredItem === 'out' && (
          <Tooltip item={trade.outputItem} visible />
        )}
      </div>

      {/* Uses */}
      <div
        style={{
          marginLeft: 'auto',
          fontSize: scale * 6,
          color: trade.uses >= trade.maxUses ? '#ff5555' : '#aaaaaa',
          whiteSpace: 'nowrap',
        }}
      >
        {trade.uses}/{trade.maxUses}
      </div>
    </div>
  )
}

export function VillagerTradeList() {
  const { windowState } = useInventoryContext()
  const { scale } = useScale()
  const [selectedIndex, setSelectedIndex] = useState(0)

  const villagerState = windowState as (typeof windowState & {
    trades?: TradeOffer[]
  }) | null

  const trades = villagerState?.trades ?? []
  if (trades.length === 0) return null

  return (
    <div
      style={{
        position: 'absolute',
        left: 4 * scale,
        top: 18 * scale,
        width: 100 * scale,
        maxHeight: 130 * scale,
        overflowY: 'auto',
        display: 'flex',
        flexDirection: 'column',
        gap: scale,
        scrollbarWidth: 'thin',
      }}
    >
      {trades.map((trade, i) => (
        <TradeRow
          key={i}
          trade={trade}
          index={i}
          selected={selectedIndex === i}
          onSelect={() => setSelectedIndex(i)}
        />
      ))}
    </div>
  )
}
