"use client"
import React, { useEffect, useRef, useState } from "react"
import Papa from "papaparse"

interface Library {
  library: string
  description: string
}

interface PythonLibrariesInputProps {
  onChange: (libraries: string[]) => void
}

export default function PythonLibrariesInput({ onChange }: PythonLibrariesInputProps) {
  const [inputValue, setInputValue] = useState("")
  const [libraries, setLibraries] = useState<Library[]>([])
  const [filteredLibraries, setFilteredLibraries] = useState<Library[]>([])
  const [selectedLibraries, setSelectedLibraries] = useState<string[]>([])
  const [showDropdown, setShowDropdown] = useState(false)
  const [highlightedIndex, setHighlightedIndex] = useState(-1)
  const inputRef = useRef<HTMLInputElement>(null)
  const dropdownRef = useRef<HTMLUListElement>(null)

  useEffect(() => {
    fetch("/popularPythonLibraries.csv")
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        return response.text()
      })
      .then(csvData => {
        const results = Papa.parse<Library>(csvData, { header: true })
        const validLibraries = results.data.filter(lib => lib.library && lib.description)
        setLibraries(validLibraries)
      })
      .catch(error => console.error("Error loading CSV:", error))
  }, [])

  useEffect(() => {
    const filtered = libraries.filter(lib =>
      lib.library?.toLowerCase().includes(inputValue.toLowerCase()),
    )
    setFilteredLibraries(filtered)
    setShowDropdown(inputValue.length > 0)
    setHighlightedIndex(0) // Always set to 0 to select the top option
  }, [inputValue, libraries])

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value)
  }

  const handleLibrarySelect = (library: string) => {
    if (!selectedLibraries.includes(library)) {
      const newSelectedLibraries = [...selectedLibraries, library]
      setSelectedLibraries(newSelectedLibraries)
      onChange(newSelectedLibraries)
    }
    setInputValue("")
    setShowDropdown(false)
    inputRef.current?.focus()
  }

  const handleRemoveLibrary = (library: string) => {
    const newSelectedLibraries = selectedLibraries.filter(lib => lib !== library)
    setSelectedLibraries(newSelectedLibraries)
    onChange(newSelectedLibraries)
  }

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "ArrowDown") {
      e.preventDefault()
      setHighlightedIndex(prevIndex =>
        prevIndex < filteredLibraries.length - 1 ? prevIndex + 1 : prevIndex,
      )
    } else if (e.key === "ArrowUp") {
      e.preventDefault()
      setHighlightedIndex(prevIndex => (prevIndex > 0 ? prevIndex - 1 : 0))
    } else if (e.key === "Enter") {
      e.preventDefault()
      if (highlightedIndex !== -1 && filteredLibraries[highlightedIndex]) {
        handleLibrarySelect(filteredLibraries[highlightedIndex].library)
      } else if (inputValue.trim() !== "") {
        handleLibrarySelect(inputValue.trim())
      }
    } else if (e.key === "Tab" && showDropdown) {
      e.preventDefault()
      if (filteredLibraries.length > 0) {
        handleLibrarySelect(filteredLibraries[0].library)
      } else if (inputValue.trim() !== "") {
        handleLibrarySelect(inputValue.trim())
      }
    } else if (
      (e.key === "Backspace" || e.key === "Delete") &&
      inputValue === "" &&
      selectedLibraries.length > 0
    ) {
      e.preventDefault()
      const newSelectedLibraries = selectedLibraries.slice(0, -1)
      setSelectedLibraries(newSelectedLibraries)
      onChange(newSelectedLibraries)
    }

    // Scroll the highlighted item into view
    if (e.key === "ArrowDown" || e.key === "ArrowUp") {
      const highlightedElement = dropdownRef.current?.children[highlightedIndex] as HTMLElement
      if (highlightedElement) {
        highlightedElement.scrollIntoView({
          behavior: "smooth",
          block: "nearest",
        })
      }
    }
  }

  return (
    <div className="relative  w-full">
      <div className="flex flex-wrap w-full items-center gap-2 p-2 rounded-sm border border-solid border-white/10 bg-white/5 focus-within:[box-shadow:0_0_4px_#1e40af] min-h-[40px]">
        {selectedLibraries.map(lib => (
          <div
            key={lib}
            className="flex items-center bg-yellow-400 text-black px-2 py-1 rounded mb-1"
          >
            {lib}
            <button className="ml-2 text-xs" onClick={() => handleRemoveLibrary(lib)}>
              ×
            </button>
          </div>
        ))}
        <div className="flex-grow">
          <input
            ref={inputRef}
            className="font-source_code_pro w-full leading-tight text-stone-400 bg-transparent outline-none placeholder:text-[#B6AFAF]"
            placeholder={
              selectedLibraries.length === 0 ? "Type to add libraries..." : "Add more..."
            }
            value={inputValue}
            onChange={handleInputChange}
            onKeyDown={handleKeyDown}
          />
        </div>
      </div>
      {showDropdown && (
        <ul
          ref={dropdownRef}
          className="absolute z-10 w-full mt-1 bg-neutral-900 border border-white/20 rounded-sm max-h-60 overflow-auto list-none p-0"
        >
          {filteredLibraries.map((lib, index) => (
            <li
              key={lib.library}
              className={`px-4 py-2 cursor-pointer group ${
                index === highlightedIndex ? "bg-yellow-400" : "hover:bg-yellow-400"
              }`}
              onClick={() => handleLibrarySelect(lib.library)}
            >
              <span
                className={`font-bold ${index === highlightedIndex ? "text-[#0B0A0A]" : "group-hover:text-[#0B0A0A]"}`}
              >
                {lib.library}
              </span>
              <span
                className={`ml-2 text-sm ${index === highlightedIndex ? "text-[#0B0A0A]" : "text-gray-400 group-hover:text-[#0B0A0A]"}`}
              >
                {lib.description}
              </span>
            </li>
          ))}
          {inputValue.trim() !== "" &&
            !filteredLibraries.some(
              lib => lib.library.toLowerCase() === inputValue.toLowerCase(),
            ) && (
              <li
                className={`px-4 py-2 cursor-pointer group ${
                  highlightedIndex === filteredLibraries.length
                    ? "bg-yellow-400"
                    : "hover:bg-yellow-400"
                }`}
                onClick={() => handleLibrarySelect(inputValue.trim())}
              >
                <span
                  className={`font-bold ${
                    highlightedIndex === filteredLibraries.length
                      ? "text-[#0B0A0A]"
                      : "group-hover:text-[#0B0A0A]"
                  }`}
                >
                  {inputValue}
                </span>
              </li>
            )}
        </ul>
      )}
    </div>
  )
}
