import { splitProps, type ComponentProps } from "solid-js"
import { Select as SelectPrimitive } from "@kobalte/core/select"
import { cn } from "@/lib/utils"
import { Check, ChevronDown } from "lucide-solid"

const Select = SelectPrimitive
const SelectValue = SelectPrimitive.Value

const SelectTrigger = (props: ComponentProps<typeof SelectPrimitive.Trigger>) => {
    const [local, others] = splitProps(props, ["class", "children"])
    return (
        <SelectPrimitive.Trigger
            class={cn(
                "flex h-9 w-full items-center justify-between rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
                local.class
            )}
            {...others}
        >
            {local.children}
            <SelectPrimitive.Icon as={ChevronDown} class="h-4 w-4 opacity-50 transition-transform duration-200" />
        </SelectPrimitive.Trigger>
    )
}

const SelectContent = (props: ComponentProps<typeof SelectPrimitive.Content>) => {
    const [local, others] = splitProps(props, ["class"])
    return (
        <SelectPrimitive.Portal>
            <SelectPrimitive.Content
                class={cn(
                    "relative z-[200] min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md animate-in fade-in-80 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",
                    local.class
                )}
                {...others}
            >
                <SelectPrimitive.Listbox class="p-1" />
            </SelectPrimitive.Content>
        </SelectPrimitive.Portal>
    )
}

const SelectItem = (props: ComponentProps<typeof SelectPrimitive.Item>) => {
    const [local, others] = splitProps(props, ["class", "children"])
    return (
        <SelectPrimitive.Item
            class={cn(
                "relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
                local.class
            )}
            {...others}
        >
            <span class="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
                <SelectPrimitive.ItemIndicator>
                    <Check class="h-4 w-4" />
                </SelectPrimitive.ItemIndicator>
            </span>
            <SelectPrimitive.ItemLabel>{local.children}</SelectPrimitive.ItemLabel>
        </SelectPrimitive.Item>
    )
}

export { Select, SelectValue, SelectTrigger, SelectContent, SelectItem }
