"use client"

import { useState, useRef, useEffect, useCallback } from "react"
import { ChevronDown, Check } from "lucide-react"
import { cn } from "@/lib/utils"

export interface SelectOption {
  value: string
  label: string
}

interface SelectProps {
  name?: string
  value?: string
  defaultValue?: string
  onChange?: (value: string) => void
  options: SelectOption[]
  placeholder?: string
  required?: boolean
  className?: string
}

export function Select({
  name,
  value,
  defaultValue = "",
  onChange,
  options,
  placeholder = "Select…",
  required,
  className,
}: SelectProps) {
  const isControlled = value !== undefined
  const [internal, setInternal] = useState(defaultValue)
  const current = isControlled ? value : internal

  const [open, setOpen] = useState(false)
  const [cursor, setCursor] = useState(-1)
  const ref = useRef<HTMLDivElement>(null)
  const listRef = useRef<HTMLDivElement>(null)

  // Close on outside click
  useEffect(() => {
    function onOutside(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false)
    }
    document.addEventListener("mousedown", onOutside)
    return () => document.removeEventListener("mousedown", onOutside)
  }, [])

  // Reset cursor when opening
  useEffect(() => {
    if (open) {
      const idx = options.findIndex((o) => o.value === current)
      setCursor(idx >= 0 ? idx : 0)
    }
  }, [open])

  // Scroll cursor into view
  useEffect(() => {
    if (!open) return
    const el = listRef.current?.querySelector(`[data-idx="${cursor}"]`) as HTMLElement
    el?.scrollIntoView({ block: "nearest" })
  }, [cursor, open])

  function pick(val: string) {
    if (!isControlled) setInternal(val)
    onChange?.(val)
    setOpen(false)
  }

  function onKeyDown(e: React.KeyboardEvent) {
    if (!open) {
      if (e.key === "Enter" || e.key === " " || e.key === "ArrowDown") {
        e.preventDefault()
        setOpen(true)
      }
      return
    }
    switch (e.key) {
      case "ArrowDown":
        e.preventDefault()
        setCursor((v) => Math.min(v + 1, options.length - 1))
        break
      case "ArrowUp":
        e.preventDefault()
        setCursor((v) => Math.max(v - 1, 0))
        break
      case "Enter":
        e.preventDefault()
        if (cursor >= 0 && options[cursor]) pick(options[cursor].value)
        break
      case "Escape":
        e.preventDefault()
        setOpen(false)
        break
      default: {
        // Jump to first option starting with typed letter
        const char = e.key.toLowerCase()
        if (char.length === 1) {
          const idx = options.findIndex((o) => o.label.toLowerCase().startsWith(char))
          if (idx >= 0) setCursor(idx)
        }
      }
    }
  }

  const selected = options.find((o) => o.value === current)

  return (
    <div ref={ref} className={cn("relative", className)}>
      {/* Hidden input for FormData / native form submission */}
      {name && (
        <input type="hidden" name={name} value={current} required={required} readOnly />
      )}

      {/* Trigger button */}
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        onKeyDown={onKeyDown}
        aria-haspopup="listbox"
        aria-expanded={open}
        className={cn(
          "w-full flex items-center justify-between gap-2 rounded-lg border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-left transition-colors",
          "hover:border-white/20 focus:outline-none focus:border-indigo-500/50 focus:ring-1 focus:ring-indigo-500",
          open && "border-indigo-500/40"
        )}
      >
        <span className={selected ? "text-white" : "text-white/30"}>
          {selected ? selected.label : placeholder}
        </span>
        <ChevronDown
          className={cn("h-4 w-4 shrink-0 text-white/30 transition-transform duration-150", open && "rotate-180")}
        />
      </button>

      {/* Dropdown */}
      {open && (
        <div
          role="listbox"
          className="absolute left-0 right-0 z-[100] mt-1.5 overflow-hidden rounded-xl border border-white/[0.08] bg-[#1d1d2a] shadow-2xl shadow-black/60"
        >
          <div ref={listRef} className="max-h-56 overflow-y-auto py-1.5">
            {options.map((opt, idx) => {
              const active = current === opt.value
              const highlighted = cursor === idx
              return (
                <button
                  key={opt.value}
                  data-idx={idx}
                  type="button"
                  role="option"
                  aria-selected={active}
                  onClick={() => pick(opt.value)}
                  onMouseEnter={() => setCursor(idx)}
                  className={cn(
                    "flex w-full items-center justify-between px-4 py-2.5 text-sm text-left transition-colors",
                    highlighted && !active && "bg-white/[0.05] text-white",
                    active
                      ? "bg-indigo-500/15 text-indigo-300"
                      : "text-white/75"
                  )}
                >
                  {opt.label}
                  {active && <Check className="h-3.5 w-3.5 shrink-0 text-indigo-400" />}
                </button>
              )
            })}
          </div>
        </div>
      )}
    </div>
  )
}
