import React, { useState, useCallback, useEffect, useRef } from 'react'
import type { RecipeNavFrame, RecipeGuide, ItemStack } from '../../types'
import { ItemCanvas } from '../ItemCanvas'
import { Tooltip } from '../Tooltip'
import { useScale } from '../../context/ScaleContext'
import { useTextures } from '../../context/TextureContext'
import { getInventoryType } from '../../registry'

function isTypingTarget(target: EventTarget | null): boolean {
  if (!target || !(target instanceof HTMLElement)) return false
  const tag = target.tagName
  if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true
  if (target.isContentEditable) return true
  return false
}

interface RecipeInventoryViewProps {
  navStack: RecipeNavFrame[]
  onBack: () => void
  onGuideIndexChange: (idx: number) => void
  /** Called when R or U is pressed while hovering a recipe item (nested navigation) */
  onPushFrame: (item: RecipeNavFrame['item'], mode: 'recipes' | 'usages') => void
}

function minecraftWikiUrlForName(nameOrDisplay: string): string {
  const slug = nameOrDisplay.replace(/ /g, '_')
  return `https://minecraft.wiki/w/${encodeURIComponent(slug)}`
}

/** Slot item with a Tooltip, used inside the recipe view */
function RecipeItemCell({
  item,
  x,
  y,
  size,
  onHover,
  onRecipeNavigate,
}: {
  item: ItemStack | null
  x: number
  y: number
  size: number
  onHover: (item: ItemStack | null) => void
  onRecipeNavigate?: (item: ItemStack, mode: 'recipes' | 'usages') => void
}) {
  const [hovered, setHovered] = useState(false)

  if (!item) {
    return (
      <div
        style={{
          position: 'absolute',
          left: x,
          top: y,
          width: size,
          height: size,
        }}
      />
    )
  }

  return (
    <div
      style={{ position: 'absolute', left: x, top: y, width: size, height: size, cursor: 'default' }}
      onMouseEnter={() => {
        setHovered(true)
        onHover(item)
      }}
      onMouseLeave={() => {
        setHovered(false)
        onHover(null)
      }}
      onClick={(e) => {
        e.stopPropagation()
        onRecipeNavigate?.(item, 'recipes')
      }}
      onContextMenu={(e) => {
        e.preventDefault()
        e.stopPropagation()
        onRecipeNavigate?.(item, 'usages')
      }}
    >
      <ItemCanvas item={item} size={size} style={{ position: 'absolute', top: 0, left: 0, pointerEvents: 'none' }} />
      {hovered && <Tooltip item={item} visible />}
    </div>
  )
}

/**
 * Renders the current recipe guide using the actual inventory background layout
 * (crafting_table for crafting, furnace for smelting). Replaces the main
 * InventoryWindow while a recipe is being browsed.
 */
export function RecipeInventoryView({
  navStack,
  onBack,
  onGuideIndexChange,
  onPushFrame,
}: RecipeInventoryViewProps) {
  const { scale, contentSize } = useScale()
  // Registry coords already point to item area — no border offset needed
  const borderPx = 0
  const frame = navStack[navStack.length - 1]
  const guide = frame.guides[frame.guideIndex]
  const hoveredItemRef = useRef<RecipeNavFrame['item'] | null>(null)
  const recipeViewRootRef = useRef<HTMLDivElement>(null)

  const handleHoverItem = useCallback((item: ItemStack | null) => {
    if (!item) { hoveredItemRef.current = null; return }
    hoveredItemRef.current = {
      type: item.type,
      name: item.name ?? '',
      displayName: item.displayName ?? item.name ?? `Item #${item.type}`,
      count: item.count,
      metadata: item.metadata,
    }
  }, [])

  const handleRecipeItemNavigate = useCallback(
    (item: ItemStack, mode: 'recipes' | 'usages') => {
      onPushFrame(
        {
          type: item.type,
          name: item.name ?? '',
          displayName: item.displayName ?? item.name ?? `Item #${item.type}`,
          count: item.count,
          metadata: item.metadata,
        },
        mode,
      )
    },
    [onPushFrame],
  )

  const wikiHref = minecraftWikiUrlForName(frame.item.name || frame.item.displayName || 'Unknown')

  // R / U for nested navigation on hovered recipe items
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.code !== 'KeyR' && e.code !== 'KeyU') return
      if (isTypingTarget(e.target)) return
      const item = hoveredItemRef.current
      if (!item) return
      onPushFrame(item, e.code === 'KeyR' ? 'recipes' : 'usages')
    }
    window.addEventListener('keydown', handler)
    return () => window.removeEventListener('keydown', handler)
  }, [onPushFrame])

  // Escape / Backspace = go back one frame (Backspace on root frame closes recipe view)
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.code !== 'Escape' && e.code !== 'Backspace') return
      if (isTypingTarget(e.target)) return
      onBack()
      if (e.code === 'Backspace') e.preventDefault()
    }
    window.addEventListener('keydown', handler)
    return () => window.removeEventListener('keydown', handler)
  }, [onBack])

  const isMultiFrame = navStack.length > 1
  const isCustom = guide.type === 'custom'

  // Determine layout type and get definition (not needed for custom)
  const layoutType = guide.type === 'smelting' ? 'furnace' : 'crafting_table'
  const def = getInventoryType(layoutType)!

  // Container-only slots (no player inv / hotbar)
  const containerSlots = isCustom ? [] : def.slots.filter(
    (s) => s.group !== 'inventory' && s.group !== 'hotbar',
  )

  // Map recipe items to slot indices
  const slotItems = new Map<number, ItemStack | null>()

  if (guide.type === 'crafting') {
    slotItems.set(0, guide.result ?? null)
    const ingr = guide.ingredients ?? []
    for (let i = 0; i < 9; i++) {
      slotItems.set(i + 1, ingr[i] ?? null)
    }
  } else if (guide.type === 'smelting') {
    slotItems.set(0, guide.input ?? null)
    slotItems.set(1, guide.fuel ?? null)
    slotItems.set(2, guide.result ?? null)
  }

  const totalGuides = frame.guides.length
  const navFontSize = Math.max(6, Math.round(6 * scale))
  const navPx = Math.max(1, Math.round(scale))

  const handleWheel = useCallback(
    (e: WheelEvent) => {
      if (totalGuides <= 1) return
      e.preventDefault()
      const idx = frame.guideIndex
      if (e.deltaY > 0) {
        onGuideIndexChange(Math.min(idx + 1, totalGuides - 1))
      } else {
        onGuideIndexChange(Math.max(idx - 1, 0))
      }
    },
    [totalGuides, frame.guideIndex, onGuideIndexChange],
  )

  useEffect(() => {
    const el = recipeViewRootRef.current
    if (!el || totalGuides <= 1) return
    el.addEventListener('wheel', handleWheel, { passive: false })
    return () => el.removeEventListener('wheel', handleWheel)
  }, [handleWheel, totalGuides])

  return (
    <div
      ref={recipeViewRootRef}
      className="mc-inv-recipe-view"
      style={{ display: 'inline-flex', flexDirection: 'column', alignItems: 'stretch' }}
    >
      {/* ── Navigation bar ABOVE the inventory background ── */}
      <div
        className="mc-inv-recipe-nav"
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: 4 * scale,
          marginBottom: 3 * scale,
          padding: `${Math.round(2 * scale)}px ${Math.round(4 * scale)}px`,
          fontSize: navFontSize,
          fontFamily: "'Minecraftia', 'Minecraft', monospace",
          background: '#c6c6c6',
          border: `${Math.max(1, Math.round(scale))}px solid #555`,
          boxSizing: 'border-box',
          width: def.backgroundWidth * scale,
        }}
      >
        <NavBtn scale={scale} onClick={onBack}>
          {isMultiFrame ? '◀ Back' : '✕ Close'}
        </NavBtn>

        {/* Mode label */}
        <span style={{ color: '#505050', flex: 1 }}>
          {frame.mode === 'recipes' ? 'Recipes for' : 'Usages of'}{' '}
          <span style={{ color: '#205090' }}>{frame.item.displayName}</span>
          {navStack.length > 1 && (
            <span style={{ color: '#aaa', marginLeft: 4 * scale }}>
              {'▸'.repeat(navStack.length - 1)}
            </span>
          )}
        </span>

        <a
          href={wikiHref}
          target="_blank"
          rel="noopener noreferrer"
          onMouseDown={(e) => e.stopPropagation()}
          onClick={(e) => e.stopPropagation()}
          style={{
            color: '#3366bb',
            textDecoration: 'underline',
            flexShrink: 0,
            whiteSpace: 'nowrap',
          }}
        >
          Wiki
        </a>

        {/* Prev / next for multiple guides */}
        {totalGuides > 1 && (
          <>
            <NavBtn
              scale={scale}
              onClick={() => onGuideIndexChange(frame.guideIndex > 0 ? frame.guideIndex - 1 : totalGuides - 1)}
            >◀</NavBtn>
            <span style={{ color: '#404040', minWidth: 40 * scale, textAlign: 'center' }}>
              {frame.guideIndex + 1} / {totalGuides}
            </span>
            <NavBtn
              scale={scale}
              onClick={() => onGuideIndexChange(frame.guideIndex < totalGuides - 1 ? frame.guideIndex + 1 : 0)}
            >▶</NavBtn>
          </>
        )}
      </div>

      {isCustom ? (
        /* ── Compact description card for non-craftable items ── */
        <DescriptionCard
          guide={guide}
          itemName={frame.item.name}
          scale={scale}
        />
      ) : (
        /* ── Cropped inventory background with container slots only (no player inv) ── */
        <CroppedRecipeBackground
          guide={guide}
          containerSlots={containerSlots}
          slotItems={slotItems}
          scale={scale}
          navPx={navPx}
          contentSize={contentSize}
          onHoverItem={handleHoverItem}
          onRecipeNavigate={handleRecipeItemNavigate}
        />
      )}

      {/* ── Hint below ── */}
      {!isCustom && (
        <div style={{
          marginTop: 2 * scale,
          textAlign: 'center',
          fontSize: Math.max(5, Math.round(5.5 * scale)),
          fontFamily: "'Minecraftia', 'Minecraft', monospace",
          color: 'rgba(80,80,80,0.7)',
          pointerEvents: 'none',
        }}>
          Hover ingredient + R / U, or left / right-click (usages)
        </div>
      )}
    </div>
  )
}

/**
 * Cropped recipe background — shows only the container area (no player inventory).
 * Crafting: crops to 80px height (title bar + 3×3 grid + result).
 * Smelting: crops to 84px height (input + fuel + result + arrow).
 */
function CroppedRecipeBackground({
  guide,
  containerSlots,
  slotItems,
  scale,
  navPx,
  contentSize,
  onHoverItem,
  onRecipeNavigate,
}: {
  guide: RecipeGuide
  containerSlots: Array<{ index: number; x: number; y: number; size?: number; group?: string }>
  slotItems: Map<number, ItemStack | null>
  scale: number
  navPx: number
  contentSize: number
  onHoverItem: (item: ItemStack | null) => void
  onRecipeNavigate?: (item: ItemStack, mode: 'recipes' | 'usages') => void
}) {
  const textures = useTextures()
  const layoutType = guide.type === 'smelting' ? 'furnace' : 'crafting_table'
  const def = getInventoryType(layoutType)!
  const bgUrl = textures.getGuiTextureUrl(def.backgroundTexture)

  // Crop height: crafting=80, furnace=84 (matches old lib's CraftingTableGuide slice)
  const CROP_H = guide.type === 'smelting' ? 84 : 80
  const SRC_W = def.backgroundWidth
  const fontSize = Math.max(6, Math.round(6 * scale))

  return (
    <div
      className="mc-inv-recipe-cropped"
      style={{
        position: 'relative',
        width: SRC_W * scale,
        height: CROP_H * scale,
        imageRendering: 'pixelated',
        display: 'inline-block',
      }}
    >
      {/* Cropped background texture */}
      <div
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          width: SRC_W,
          height: CROP_H,
          overflow: 'hidden',
          transform: `scale(${scale})`,
          transformOrigin: 'top left',
        }}
      >
        <img
          src={bgUrl}
          alt=""
          aria-hidden
          draggable={false}
          style={{
            display: 'block',
            width: SRC_W,
            imageRendering: 'pixelated',
            pointerEvents: 'none',
            userSelect: 'none',
            objectFit: 'none',
            objectPosition: '0 0',
          }}
        />
      </div>

      {/* Title */}
      <div
        style={{
          position: 'absolute',
          top: 6 * scale,
          left: 8 * scale,
          fontSize,
          fontFamily: "'Minecraftia', 'Minecraft', monospace",
          color: '#404040',
          lineHeight: 1,
          pointerEvents: 'none',
        }}
      >
        {guide.title}
        {guide.description && (
          <span style={{ color: '#808080', marginLeft: 4 * scale }}>
            ({guide.description})
          </span>
        )}
      </div>

      {/* Slot items */}
      {containerSlots.map((slotDef) => {
        const item = slotItems.get(slotDef.index) ?? null
        return (
          <RecipeItemCell
            key={slotDef.index}
            item={item}
            x={slotDef.x * scale}
            y={slotDef.y * scale}
            size={slotDef.size ? slotDef.size * scale - 2 * navPx : contentSize}
            onHover={onHoverItem}
            onRecipeNavigate={onRecipeNavigate}
          />
        )
      })}
    </div>
  )
}

/**
 * Compact description card for non-craftable items (replaces full inventory background).
 * Mirrors the old canvas-based GenericDescription layout: cropped crafting_table header,
 * gray content area, item icon, description text, and a Minecraft Wiki link.
 */
function DescriptionCard({
  guide,
  itemName,
  scale,
}: {
  guide: RecipeGuide
  itemName: string
  scale: number
}) {
  const textures = useTextures()
  const craftingDef = getInventoryType('crafting_table')!
  const bgUrl = textures.getGuiTextureUrl(craftingDef.backgroundTexture)

  const CARD_W = 176
  const CARD_H = 120
  const TITLE_H = 15
  const fontSize = Math.max(6, Math.round(6 * scale))
  const iconSize = 16 * scale

  return (
    <div
      className="mc-inv-description-card"
      style={{
        position: 'relative',
        width: CARD_W * scale,
        height: CARD_H * scale,
        imageRendering: 'pixelated',
        display: 'inline-block',
      }}
    >
      {/* Cropped crafting_table texture as background header */}
      <div
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          width: CARD_W,
          height: CARD_H,
          overflow: 'hidden',
          transform: `scale(${scale})`,
          transformOrigin: 'top left',
        }}
      >
        <img
          src={bgUrl}
          alt=""
          aria-hidden
          draggable={false}
          style={{
            display: 'block',
            width: CARD_W,
            imageRendering: 'pixelated',
            pointerEvents: 'none',
            userSelect: 'none',
            objectFit: 'none',
            objectPosition: '0 0',
          }}
        />
      </div>

      {/* Gray content overlay (below title bar) */}
      <div
        style={{
          position: 'absolute',
          top: TITLE_H * scale,
          left: 3 * scale,
          width: (CARD_W - 6) * scale,
          height: (CARD_H - TITLE_H) * scale,
          background: '#c6c6c6',
        }}
      />

      {/* Title */}
      <div
        style={{
          position: 'absolute',
          top: 6 * scale,
          left: 8 * scale,
          fontSize,
          fontFamily: "'Minecraftia', 'Minecraft', monospace",
          color: '#404040',
          lineHeight: 1,
          pointerEvents: 'none',
        }}
      >
        {guide.title}
      </div>

      {/* Item icon */}
      <div style={{ position: 'absolute', top: (TITLE_H + 3) * scale, left: 5 * scale }}>
        <ItemCanvas
          item={{ type: 0, name: itemName, displayName: guide.title, count: 1 }}
          size={iconSize}
          style={{ pointerEvents: 'none' }}
        />
      </div>

      {/* Description text */}
      {guide.description && (
        <div style={{
          position: 'absolute',
          top: (TITLE_H + 3) * scale,
          left: (5 + 18) * scale,
          right: 8 * scale,
          fontSize,
          fontFamily: "'Minecraftia', 'Minecraft', monospace",
          color: '#404040',
          lineHeight: 1.6,
          pointerEvents: 'none',
          whiteSpace: 'pre-wrap',
          wordBreak: 'break-word',
        }}>
          {guide.description}
        </div>
      )}
    </div>
  )
}

function NavBtn({
  scale,
  onClick,
  disabled,
  title,
  children,
}: {
  scale: number
  onClick: () => void
  disabled?: boolean
  title?: string
  children: React.ReactNode
}) {
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      title={title}
      style={{
        background: disabled ? '#8b8b8b' : '#c6c6c6',
        border: `${Math.max(1, Math.round(scale))}px solid #555`,
        color: disabled ? '#666' : '#404040',
        fontFamily: 'inherit',
        fontSize: 'inherit',
        cursor: disabled ? 'default' : 'pointer',
        padding: `${Math.round(scale)}px ${Math.round(3 * scale)}px`,
        lineHeight: 1,
        outline: 'none',
        flexShrink: 0,
        display: 'inline-flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      {children}
    </button>
  )
}
