"use client";

import React from "react";
import { ChevronDown } from "@untitledui/icons";
import {
    Button as AriaButton,
    ListBox as AriaListBox,
    Popover as AriaPopover,
    Select as AriaSelect,
    SelectValue as AriaSelectValue,
    type SelectProps as AriaSelectProps,
} from "react-aria-components";
import { HintText } from '../input/hint-text';
import { Label } from '../input/label';
import { cx } from '../../../utils/cx';

export interface SelectProps<T extends object> extends Omit<AriaSelectProps<T>, 'children'> {
    label?: string;
    hint?: string;
    placeholder?: string;
    children: React.ReactNode;
    className?: string;
}

export function Select<T extends object>({
    label,
    hint,
    placeholder = "Select an option",
    isInvalid,
    isDisabled,
    isRequired,
    children,
    className,
    ...props
}: SelectProps<T>) {
    return (
        <AriaSelect
            {...props}
            isInvalid={isInvalid}
            isDisabled={isDisabled}
            isRequired={isRequired}
            className={cx("flex flex-col gap-1.5", className)}
        >
            {label && <Label>{label}</Label>}
            <AriaButton
                className={({ isFocusVisible, isDisabled }) =>
                    cx(
                        "flex items-center justify-between w-full rounded-sm bg-white px-3 py-2.5 text-base font-body text-fg-primary shadow-sm ring-1 ring-secondary ring-inset transition-shadow duration-100 ease-linear",
                        isFocusVisible && !isDisabled && "ring-2 ring-focus-ring",
                        isDisabled && "cursor-not-allowed bg-primary text-secondary ring-secondary",
                        isInvalid && "ring-error_subtle",
                    )
                }
            >
                <AriaSelectValue className="flex-1 text-left placeholder-shown:text-secondary">
                    {({ selectedText }) => selectedText || placeholder}
                </AriaSelectValue>
                <ChevronDown className="size-5 text-secondary" />
            </AriaButton>
            {hint && <HintText>{hint}</HintText>}
            <AriaPopover
                className="w-[--trigger-width] rounded-sm bg-white shadow-lg ring-1 ring-secondary overflow-auto max-h-60"
            >
                <AriaListBox className="outline-none p-1">
                    {children}
                </AriaListBox>
            </AriaPopover>
        </AriaSelect>
    );
}

import { registerThemeVariant } from '../../../lib/component-registry';
registerThemeVariant('select', 'aman', Select);
