"use client"

import * as React from "react"
import { Check, ChevronsUpDown, Search } from "lucide-react"
import { Command } from "cmdk"
import * as PopoverPrimitive from "@radix-ui/react-popover"

import { cn } from "@/lib/utils"

// Minimal Popover implementation since we don't have full shadcn setup
const Popover = PopoverPrimitive.Root
const PopoverTrigger = PopoverPrimitive.Trigger
const PopoverContent = React.forwardRef<
    React.ElementRef<typeof PopoverPrimitive.Content>,
    React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
    <PopoverPrimitive.Portal>
        <PopoverPrimitive.Content
            ref={ref}
            align={align}
            sideOffset={sideOffset}
            className={cn(
                "z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 bg-zinc-900 border-zinc-800 text-zinc-200",
                className
            )}
            {...props}
        />
    </PopoverPrimitive.Portal>
))
PopoverContent.displayName = PopoverPrimitive.Content.displayName

interface LanguageSelectorProps {
    language: string
    onChange: (value: string) => void
    languages: string[]
}

export function LanguageSelector({ language, onChange, languages }: LanguageSelectorProps) {
    const [open, setOpen] = React.useState(false)
    const [search, setSearch] = React.useState("")
    const listboxId = React.useId()

    const filteredLanguages = languages.filter((lang) =>
        lang.toLowerCase().includes(search.toLowerCase())
    )

    // Manual 'all' option plus filtered list
    const items = ["auto", ...filteredLanguages]

    return (
        <Popover open={open} onOpenChange={setOpen}>
            <PopoverTrigger asChild>
                <button
                    role="combobox"
                    aria-expanded={open}
                    aria-controls={listboxId}
                    className="flex items-center justify-between gap-2 px-2 py-1 text-xs font-medium text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800/50 rounded transition-colors outline-none"
                    onClick={(e) => e.stopPropagation()} // Prevent editor focus loss if possible, though specific to Tiptap needs
                >
                    {language || "Start coding..."}
                    <ChevronsUpDown className="ml-1 h-3 w-3 shrink-0 opacity-50" />
                </button>
            </PopoverTrigger>
            <PopoverContent className="w-[200px] p-0 bg-[#1e1e1e] border-[#333] text-zinc-300 shadow-xl rounded-lg overflow-hidden">
                <Command className="flex h-full w-full flex-col overflow-hidden rounded-md bg-transparent">
                    <div className="flex items-center border-b border-[#333] px-3">
                        <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
                        <input
                            className="flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50"
                            placeholder="Search language..."
                            value={search}
                            onChange={(e) => setSearch(e.target.value)}
                        />
                    </div>
                    <div id={listboxId} className="max-h-[200px] overflow-y-auto p-1 scrollbar-thin scrollbar-thumb-zinc-700">
                        {items.length === 0 && (
                            <div className="py-6 text-center text-sm">No language found.</div>
                        )}
                        {items.map((framework) => (
                            <div
                                key={framework}
                                onClick={() => {
                                    onChange(framework === "auto" ? "null" : framework)
                                    setOpen(false)
                                    setSearch("")
                                }}
                                className={cn(
                                    "relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-zinc-800 hover:text-white data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
                                    language === framework ? "bg-zinc-800 text-white" : ""
                                )}
                            >
                                <Check
                                    className={cn(
                                        "mr-2 h-4 w-4",
                                        language === framework ? "opacity-100" : "opacity-0"
                                    )}
                                />
                                {framework === "null" ? "Auto" : framework}
                            </div>
                        ))}
                    </div>
                </Command>
            </PopoverContent>
        </Popover>
    )
}
