"use client"

import { Button } from "@/components/ui/button"
import {
    Command,
    CommandEmpty,
    CommandGroup,
    CommandInput,
    CommandItem,
    CommandList
} from "@/components/ui/command"
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from "@/components/ui/popover"
import { useInView } from "@/lib/hooks"
import { useLanguage } from "@/lib/language-context"
import { cn } from "@/lib/utils"
import { Check, ChevronsUpDown, Loader2 } from "lucide-react"
import * as React from "react"

interface AsyncComboboxProps {
    value: string
    onSelect: (value: string) => void
    placeholder?: string
    searchPlaceholder?: string
    emptyMessage?: string
    className?: string
    items: { value: string; label: string }[]
    isLoading?: boolean
    hasMore?: boolean
    onLoadMore?: () => void
    onSearch?: (query: string) => void
    renderItem?: (item: { value: string; label: string }) => React.ReactNode
}

export function AsyncCombobox({
    value,
    onSelect,
    placeholder,
    searchPlaceholder,
    emptyMessage,
    className,
    items,
    isLoading = false,
    hasMore = false,
    onLoadMore,
    onSearch,
    renderItem,
}: AsyncComboboxProps) {
    const { t } = useLanguage()
    const [open, setOpen] = React.useState(false)
    const { ref, inView } = useInView()
    const [query, setQuery] = React.useState("")
    const resolvedPlaceholder = placeholder || t('common.selectOption')
    const resolvedSearchPlaceholder = searchPlaceholder || t('common.search')
    const resolvedEmptyMessage = emptyMessage || t('common.noOptionsFound')

    // Debounce search
    React.useEffect(() => {
        const timer = setTimeout(() => {
            onSearch?.(query)
        }, 300)

        return () => clearTimeout(timer)
    }, [query, onSearch])

    // Load more when scrolling to bottom
    React.useEffect(() => {
        if (inView && hasMore && !isLoading) {
            onLoadMore?.()
        }
    }, [inView, hasMore, isLoading, onLoadMore])

    const selectedItem = items.find((item) => item.value === value)

    return (
        <Popover open={open} onOpenChange={setOpen} modal={true}>
            <PopoverTrigger asChild>
                <Button
                    variant="outline"
                    role="combobox"
                    aria-expanded={open}
                    className={cn("w-full justify-between", className)}
                >
                    {selectedItem ? (
                        renderItem ? renderItem(selectedItem) : selectedItem.label
                    ) : (
                        resolvedPlaceholder
                    )}
                    <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                </Button>
            </PopoverTrigger>
            <PopoverContent className="w-[--radix-popover-trigger-width] p-0 bg-white" align="start">
                <Command shouldFilter={false}>
                    <CommandInput
                        placeholder={resolvedSearchPlaceholder}
                        value={query}
                        onValueChange={setQuery}
                        autoFocus
                        className="bg-slate-50"
                    />
                    <CommandList className="max-h-[300px] overflow-y-auto">
                        {items.length === 0 && !isLoading && (
                            <CommandEmpty>{resolvedEmptyMessage}</CommandEmpty>
                        )}
                        <CommandGroup>
                            {items.map((item) => (
                                <CommandItem
                                    key={item.value}
                                    value={item.value}
                                    onSelect={(currentValue) => {
                                        onSelect(currentValue === value ? "" : currentValue)
                                        setOpen(false)
                                    }}
                                >
                                    <Check
                                        className={cn(
                                            "mr-2 h-4 w-4",
                                            value === item.value ? "opacity-100" : "opacity-0"
                                        )}
                                    />
                                    {renderItem ? renderItem(item) : item.label}
                                </CommandItem>
                            ))}

                            {hasMore && (
                                <CommandItem disabled className="p-0 bg-transparent data-[disabled]:opacity-100">
                                    <div ref={ref} className="py-2 flex justify-center text-sm text-muted-foreground w-full">
                                        {isLoading ? (
                                            <Loader2 className="h-4 w-4 animate-spin" />
                                        ) : (
                                            <span className="h-4 block" />
                                        )}
                                    </div>
                                </CommandItem>
                            )}
                        </CommandGroup>
                    </CommandList>
                </Command>
            </PopoverContent>
        </Popover>
    )
}
