import { useAtom, useAtomValue, useSetAtom } from 'jotai'
import { useEffect } from 'react'
import { FaArrowLeft, FaArrowRight } from 'react-icons/fa'
import {
  clearItemSelectionActionAtom,
  currentCharacterInventoryAtom,
  filteredCharacterItemsAtom,
  inventoryPageRangeAtom,
  itemSelectionSelectAllFilterActionAtom,
  itemSelectionSelectAllPageActionAtom,
  moveSelectedItemsAtom,
  openMoveConfirmationAtom,
  paginateInventoryActionAtom,
  preferenceInventorySearch,
  selectedCharacterAtom,
} from '@/state/atoms'
import { MoveConfirmationPopup } from './MoveConfirmationPopup'
import { InventoryTargetSelector } from './movetarget'
import { InventoryTable } from './table'
import { InventoryFilters } from './InventoryFilters'

const InventoryRangeDisplay = () => {
  const inventoryRange = useAtomValue(inventoryPageRangeAtom)
  const items = useAtomValue(filteredCharacterItemsAtom)
  
  return (
    <div className="flex items-center px-2 bg-yellow-100 border border-black-1 whitespace-pre select-none">
      {inventoryRange.start}..{inventoryRange.end}/{items.length}
    </div>
  )
}


export const Inventory = () => {
  const selectedCharacter = useAtomValue(selectedCharacterAtom)
  const clearItemSelection = useSetAtom(clearItemSelectionActionAtom)
  const { refetch: refetchInventory } = useAtomValue(currentCharacterInventoryAtom)

  const addPageItemSelection = useSetAtom(itemSelectionSelectAllPageActionAtom)
  const addFilterItemSelection = useSetAtom(itemSelectionSelectAllFilterActionAtom)
  const [search, setSearch] = useAtom(preferenceInventorySearch)

  const paginateInventory = useSetAtom(paginateInventoryActionAtom)
  const openMoveConfirmation = useSetAtom(openMoveConfirmationAtom)
  const moveSelectedItems = useSetAtom(moveSelectedItemsAtom)

  // Add keyboard navigation
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Don't paginate if user is typing in an input
      if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
        return
      }

      if (e.key === 'ArrowLeft') {
        e.preventDefault()
        paginateInventory(-1)
      } else if (e.key === 'ArrowRight') {
        e.preventDefault()
        paginateInventory(1)
      }
    }

    window.addEventListener('keydown', handleKeyDown)
    return () => {
      window.removeEventListener('keydown', handleKeyDown)
    }
  }, [paginateInventory])

  if (!selectedCharacter) {
    return <div>select a character</div>
  }
  return (
    <div className={`flex flex-col h-full w-full`}>
      <div className="flex flex-col py-2 flex-0 justify-between h-full">
        <div className="flex flex-col gap-2">
          <div className="flex flex-row gap-0 items-center justify-between">
            <div className="flex flex-row gap-0 items-stretch">
              <button
                type="button"
                className="hover:cursor-pointer border border-black-1 bg-blue-200 hover:bg-blue-300 px-2 py-1"
                onClick={() => {
                  if (selectedCharacter) {
                    refetchInventory()
                  }
                }}
                title="Refresh inventory"
              >
                ↻
              </button>
              <input
                type="text"
                value={search}
                className="border border-black-1 px-2 py-1"
                placeholder="search..."
                onChange={e => {
                  setSearch(e.target.value)
                }}
              />
              <button
                type="button"
                className="hover:cursor-pointer border border-black-1 bg-green-200 hover:bg-green-300 px-2 flex items-center justify-center"
                onClick={() => {
                  paginateInventory(-1)
                }}
                aria-label="Previous page"
                title="Previous page (← arrow key)"
              >
                <FaArrowLeft />
              </button>
              <button
                type="button"
                className="hover:cursor-pointer border border-black-1 bg-green-200 hover:bg-green-300 px-2 flex items-center justify-center"
                onClick={() => {
                  paginateInventory(1)
                }}
                aria-label="Next page"
                title="Next page (→ arrow key)"
              >
                <FaArrowRight />
              </button>
              <InventoryRangeDisplay />
            </div>
            <div className="flex flex-row gap-0">
              <InventoryTargetSelector />
              <button
                type="button"
                onClick={async e => {
                  if (e.shiftKey) {
                    // Shift+click: skip confirmation
                    const result = await moveSelectedItems()
                    if (result.successCount > 0) {
                      clearItemSelection()
                    }
                  } else {
                    // Normal click: show confirmation
                    openMoveConfirmation()
                  }
                }}
                className="hover:cursor-pointer whitespace-preborder border-black-1 bg-orange-200 hover:bg-orange-300 px-2 py-1"
                title="Click to move with confirmation, Shift+Click to move immediately"
              >
                Move Selected
              </button>
            </div>
          </div>
          <div className="flex flex-row gap-0">
            <button
              type="button"
              className="whitespace-pre bg-purple-200 px-2 py-1 hover:cursor-pointer hover:bg-purple-300 border border-black-1"
              onClick={() => {
                addFilterItemSelection()
              }}
            >
              select filtered
            </button>
            <button
              type="button"
              className="whitespace-pre bg-cyan-200 px-2 py-1 hover:cursor-pointer hover:bg-cyan-300 border border-black-1"
              onClick={() => {
                addPageItemSelection()
              }}
            >
              select page
            </button>
            <button
              type="button"
              className="whitespace-pre bg-red-200 px-2 py-1 hover:cursor-pointer hover:bg-red-300 border border-black-1"
              onClick={() => {
                clearItemSelection()
              }}
            >
              clear
            </button>
          </div>
        </div>
      </div>
      <div className="flex flex-row justify-between items-center">
        <InventoryFilters />
        <InventoryRangeDisplay />
      </div>
      <div className="flex flex-col flex-1 h-full border border-black-2">
        <InventoryTable />
      </div>
      <MoveConfirmationPopup />
    </div>
  )
}
