import React, { useMemo } from 'react'
import type { SlotState } from '../../types'
import { getInventoryType } from '../../registry'
import { useInventoryContext } from '../../context/InventoryContext'
import { useScale } from '../../context/ScaleContext'
import { useKeyboardShortcuts } from '../../hooks/useKeyboardShortcuts'
import { Slot } from '../Slot'
import { InventoryBackground } from './InventoryBackground'
import { ProgressBar } from './ProgressBar'
import { VillagerTradeList } from './VillagerTradeList'
import { EnchantmentOptions } from './EnchantmentOptions'
import { HotbarExtras } from './HotbarExtras'
import { AnvilInput } from './AnvilInput'
import { AnvilCost } from './AnvilCost'
import { EntityDisplay } from './EntityDisplay'
import { BeaconEffects } from './BeaconEffects'

interface InventoryWindowProps {
  type: string
  title?: string
  slots?: SlotState[]
  properties?: Record<string, number>
  className?: string
  style?: React.CSSProperties
  enableKeyboardShortcuts?: boolean
  showDebug?: boolean
  /** When true, entity slot shows layout debug bounds instead of the default placeholder image. */
  entityDisplayDebug?: boolean
  /** Override entity display rendering. Pass a function returning JSX, or null to hide. */
  renderEntity?: ((width: number, height: number) => React.ReactNode) | null
}

export function InventoryWindow({
  type,
  title,
  slots: slotsProp,
  properties = {},
  className,
  style,
  enableKeyboardShortcuts = true,
  showDebug = false,
  entityDisplayDebug = false,
  renderEntity,
}: InventoryWindowProps) {
  const def = getInventoryType(type)
  const { windowState, getSlot } = useInventoryContext()
  const { scale, slotSize, contentSize } = useScale()
  // borderPx removed from slot positioning: registry coords already point to the item area
  const borderPx = 0
  const isHotbar = type === 'hotbar'

  useKeyboardShortcuts(enableKeyboardShortcuts && !isHotbar)

  const effectiveSlots = useMemo(() => {
    if (slotsProp) return slotsProp
    return windowState?.slots ?? []
  }, [slotsProp, windowState])

  const effectiveProperties = useMemo(() => {
    return { ...properties, ...(windowState?.properties ?? {}) }
  }, [properties, windowState])

  if (!def) {
    return (
      <div style={{ color: 'red', padding: 8 }}>
        Unknown inventory type: {type}
      </div>
    )
  }

  // Player inventory: don't show title (it's just the player's own inventory)
  // Beacon: vanilla overrides renderLabels to show "Primary/Secondary Power" instead of title
  const isBeacon = def?.name === 'beacon'
  const effectiveTitle = (type === 'player' || isBeacon) ? undefined : (title ?? windowState?.title ?? def.title)
  const isVillager = type === 'villager'
  const isEnchanting = def?.name === 'enchanting_table'
  const isAnvil = def?.name === 'anvil'

  const resolveItem = (slotIndex: number) => {
    const fromProp = effectiveSlots.find((s) => s.index === slotIndex)
    if (fromProp) return fromProp.item
    return getSlot(slotIndex)?.item ?? null
  }

  return (
    <div
      className={['mc-inv-root', className].filter(Boolean).join(' ')}
      style={{ position: 'relative', display: 'inline-block', ...style }}
    >
      <InventoryBackground definition={def} title={effectiveTitle} showDebug={showDebug}>
        {/* Render slots */}
        {def.slots.map((slotDef) => (
          <div
            key={slotDef.index}
            className="mc-inv-slot-wrapper"
            style={{
              position: 'absolute',
              // Offset by borderPx to land inside the texture's slot cell (skip the 1px border)
              left: slotDef.x * scale + borderPx,
              top: slotDef.y * scale + borderPx,
            }}
          >
            <Slot
              index={slotDef.index}
              item={resolveItem(slotDef.index)}
              size={slotDef.size ? slotDef.size * scale - 2 * borderPx : contentSize}
              resultSlot={slotDef.resultSlot}
              label={slotDef.label}
              disableFocusSwap={isHotbar}
            />
          </div>
        ))}

        {/* Entity display area */}
        {def.entityDisplay && def.entityPlaceholder && (
          <EntityDisplay
            area={def.entityDisplay}
            placeholder={def.entityPlaceholder}
            debug={entityDisplayDebug}
            renderEntity={renderEntity}
          />
        )}

        {/* Progress bars */}
        {def.progressBars?.map((pb) => (
          <ProgressBar
            key={pb.id}
            definition={pb}
            properties={effectiveProperties}
            backgroundTexture={def.backgroundTexture}
          />
        ))}

        {/* Villager trades */}
        {isVillager && <VillagerTradeList />}

        {/* Enchanting options */}
        {isEnchanting && (
          <EnchantmentOptions
            properties={effectiveProperties}
            x={60}
            y={14}
          />
        )}

        {/* Anvil rename input + cost display */}
        {isAnvil && <AnvilInput x={59} y={20} width={110} height={16} />}
        {isAnvil && <AnvilCost properties={effectiveProperties} backgroundWidth={def.backgroundWidth} />}

        {/* Beacon effect selection panel */}
        {isBeacon && <BeaconEffects properties={effectiveProperties} />}

        {/* Hotbar extras: active slot indicator, offhand slot, open-inventory button */}
        {isHotbar && (
          <HotbarExtras
            showOffhand={Boolean(effectiveProperties.showOffhand)}
            container={Boolean(effectiveProperties.container)}
            offhandItem={resolveItem(45)}
          />
        )}
      </InventoryBackground>
    </div>
  )
}
