import React, { useEffect } from "react"
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover"
import { Button } from "../ui/button"
import { ChevronsUpDown, Check } from "lucide-react"
import { Command, CommandInput, CommandEmpty, CommandGroup, CommandItem } from "../ui/command"

type Item = {
    id: number
    title: string
}

type Props = {
    title: string
    items: Item[]
    selected: number[]
    onSelected: (ids: number[]) => void
    edit?: boolean
    disabled?: boolean
    error?: string
}

export default function ItemSelector({
    title,
    items,
    selected,
    onSelected,
    edit = true,
    disabled = false,
    error
}: Props) {
    const [open, setOpen] = React.useState(false)

    const toggleItem = (id: number) => {
        onSelected(selected.includes(id) ? selected.filter(i => i !== id) : [...selected, id])
    }

    return (
        <div className="flex-1 flex flex-col gap-2">
            <label className="text-sm font-medium">{title}</label>

            {/* Selected Items */}
            {selected.length > 0 ? (
                <div className="flex flex-wrap gap-2 max-w-lg">
                    {items
                        .filter(i => selected.includes(i.id))
                        .map(item => (
                            <div
                                key={item.id}
                                className="flex items-center justify-between gap-4 px-4 py-1.5 text-center border rounded-sm text-sm bg-background w-fit"
                            >
                                <span>{item.title}</span>
                            </div>
                        ))}
                </div>
            ) : (
                <div className="flex items-center justify-center p-2 w-fit gap-4 border border-dashed rounded-sm text-muted-foreground">
                    <p className="text-sm">No {title.toLowerCase()} selected yet.</p>
                </div>
            )}

            {error && <p className='text-red-600 text-sm'>{error}</p>}

            {/* Selector Popover */}
            {edit && (
                <Popover open={open} onOpenChange={setOpen}>
                    <PopoverTrigger asChild>
                        <Button disabled={disabled} size="sm" variant="outline" role="combobox" className="w-fit justify-between">
                            Select <ChevronsUpDown className="ml-2 h-4 w-4 opacity-50" />
                        </Button>
                    </PopoverTrigger>

                    <PopoverContent className="p-0">
                        <Command>
                            <CommandInput placeholder={`Search ${title.toLowerCase()}...`} />
                            <CommandEmpty>No results found.</CommandEmpty>
                            <CommandGroup>
                                {/* <CommandItem key="all" onSelect={() => toggleItem("all")}>
                                    <span className="font-medium">All {title}</span>
                                    <Check className={`h-5 w-5 ml-auto ${selected.length === items.length ? "opacity-100" : "opacity-0"}`} />
                                </CommandItem> */}
                                {items.map(item => {
                                    const isActive = selected.includes(item.id)
                                    return (
                                        <CommandItem key={item.id} onSelect={() => toggleItem(item.id)} className="flex items-center justify-between p-2 cursor-pointer hover:bg-muted">
                                            <span>{item.title}</span>
                                            <Check className={`h-5 w-5 ml-auto ${isActive ? "opacity-100" : "opacity-0"}`} />
                                        </CommandItem>
                                    )
                                })}
                            </CommandGroup>
                        </Command>
                    </PopoverContent>
                </Popover>
            )}
        </div>
    )
}