import React, { useState, useCallback, useRef, useEffect } from 'react'
import { useFocusInputShortcut } from '../../hooks/useFocusInputShortcut'
import { useScale } from '../../context/ScaleContext'
import { useTextures } from '../../context/TextureContext'
import { useInventoryContext } from '../../context/InventoryContext'

const ANVIL_FOCUS_KEYS = ['KeyE'] as const

interface AnvilInputProps {
  x: number
  y: number
  width: number
  height: number
}

export function AnvilInput({ x, y, width, height }: AnvilInputProps) {
  const { scale } = useScale()
  const textures = useTextures()
  const { sendAction, windowState } = useInventoryContext()

  const [text, setText] = useState('')
  const [focused, setFocused] = useState(false)
  const inputRef = useRef<HTMLInputElement>(null)

  const hasInputItem = windowState?.slots.some((s) => s.index === 0 && s.item !== null) ?? false

  useFocusInputShortcut(inputRef, ANVIL_FOCUS_KEYS, hasInputItem)

  const textFieldUrl = textures.getGuiTextureUrl(
    hasInputItem
      ? '1.21.11/textures/gui/sprites/container/anvil/text_field.png'
      : '1.21.11/textures/gui/sprites/container/anvil/text_field_disabled.png',
  )

  useEffect(() => {
    if (!hasInputItem) {
      setText('')
      setFocused(false)
    }
  }, [hasInputItem])

  const handleChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const val = e.target.value
      setText(val)
      sendAction({ type: 'rename', text: val })
    },
    [sendAction],
  )

  return (
    <div
      className="mc-inv-anvil-input"
      style={{
        position: 'absolute',
        left: x * scale,
        top: y * scale,
        width: width * scale,
        height: height * scale,
        imageRendering: 'pixelated',
      }}
    >
      <img
        src={textFieldUrl}
        alt=""
        aria-hidden
        draggable={false}
        style={{
          position: 'absolute',
          inset: 0,
          width: '100%',
          height: '100%',
          imageRendering: 'pixelated',
          pointerEvents: 'none',
        }}
      />
      <input
        ref={inputRef}
        type="text"
        value={text}
        onChange={handleChange}
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        disabled={!hasInputItem}
        maxLength={35}
        placeholder=""
        className="mc-inv-anvil-rename-input"
        style={{
          position: 'absolute',
          left: 2 * scale,
          top: 1 * scale,
          width: (width - 4) * scale,
          height: (height - 2) * scale,
          border: 'none',
          outline: 'none',
          background: 'transparent',
          color: '#ffffff',
          fontFamily: "'Minecraftia', 'Minecraft', monospace",
          fontSize: 7 * scale,
          padding: 0,
          lineHeight: 1,
          caretColor: focused ? '#ffffff' : 'transparent',
        }}
      />
    </div>
  )
}
