import React, { useCallback, useEffect, useRef } from 'react'
import { useCloseOnWClick } from './hooks/useCloseOnWClick'
import type { InventoryConnector } from './connector/types'
import type { SlotState } from './types'
import { InventoryProvider } from './context/InventoryContext'
import { ScaleProvider } from './context/ScaleContext'
import { TextureProvider } from './context/TextureContext'
import { InventoryWindow } from './components/InventoryWindow'
import { CursorItem } from './components/CursorItem'
import { JEI } from './components/JEI'
import type { JEIItem } from './components/JEI'
import type { TextureConfig } from './context/TextureContext'
import './styles/tokens.css'

export interface InventoryGUIProps {
  type: string
  title?: string
  slots?: SlotState[]
  properties?: Record<string, number>
  connector?: InventoryConnector | null
  scale?: number
  showJEI?: boolean
  jeiItems?: JEIItem[]
  jeiPosition?: 'left' | 'right'
  textureBaseUrl?: string
  textureConfig?: Partial<TextureConfig>
  enableKeyboardShortcuts?: boolean
  /** Hide empty slot labels like Head, Chest, Legs, Feet */
  noPlaceholders?: boolean
  onClose?: () => void
  className?: string
  style?: React.CSSProperties
}

export function InventoryGUI({
  type,
  title,
  slots,
  properties,
  connector = null,
  scale = 2,
  showJEI = false,
  jeiItems = [],
  jeiPosition = 'right',
  textureBaseUrl,
  textureConfig,
  enableKeyboardShortcuts = true,
  noPlaceholders = false,
  onClose,
  className,
  style,
}: InventoryGUIProps) {
  const containerRef = useRef<HTMLDivElement>(null)

  useCloseOnWClick(onClose)

  const handleClose = useCallback(
    (e: KeyboardEvent) => {
      if (e.code === 'Escape') onClose?.()
    },
    [onClose],
  )

  useEffect(() => {
    if (!onClose) return
    window.addEventListener('keydown', handleClose)
    return () => window.removeEventListener('keydown', handleClose)
  }, [handleClose, onClose])

  return (
    <TextureProvider baseUrl={textureBaseUrl} config={textureConfig}>
      <ScaleProvider scale={scale}>
        <InventoryProvider connector={connector} noPlaceholders={noPlaceholders}>
          <div
            ref={containerRef}
            className={className}
            style={{
              display: 'flex',
              alignItems: 'flex-start',
              gap: 4 * scale,
              ...style,
            }}
          >
            {showJEI && jeiPosition === 'left' && (
              <JEI
                items={jeiItems}
                position="left"
                style={{ alignSelf: 'stretch' }}
              />
            )}

            <InventoryWindow
              type={type}
              title={title}
              slots={slots}
              properties={properties}
              enableKeyboardShortcuts={enableKeyboardShortcuts}
            />

            {showJEI && jeiPosition === 'right' && (
              <JEI
                items={jeiItems}
                position="right"
                style={{ alignSelf: 'stretch' }}
              />
            )}
          </div>

          <CursorItem />
        </InventoryProvider>
      </ScaleProvider>
    </TextureProvider>
  )
}
