import { cn } from '@/lib/cn';
import { ChevronDown } from 'lucide-react';
import { forwardRef, type SelectHTMLAttributes } from 'react';

type SelectProps = SelectHTMLAttributes<HTMLSelectElement> & {
    invalid?: boolean;
    /** Classes for the wrapper (e.g. width: `w-full`, `w-40`). Defaults to
     *  full width. */
    wrapperClassName?: string;
};

/**
 * Styled native `<select>` — visually matched to `Input` (same height, border,
 * radius, focus ring) with the browser chevron replaced by a properly-placed
 * `ChevronDown`. Drop-in for raw `<select>`: pass `value`/`onChange`/`<option>`
 * children as usual.
 */
export const Select = forwardRef<HTMLSelectElement, SelectProps>(
    ({ className, wrapperClassName, invalid, children, ...props }, ref) => (
        // h-fit pins the wrapper to the select's own height — without it,
        // grid/flex parents stretch the wrapper to the row and the
        // absolutely-positioned chevron centers on the wrong box.
        <div className={cn('relative h-fit', wrapperClassName ?? 'w-full')}>
            <select
                ref={ref}
                aria-invalid={invalid || undefined}
                className={cn(
                    // h-10 matches Input + Button md — see Input.tsx.
                    'block h-10 w-full appearance-none rounded-lg border bg-card py-2 pl-3 pr-9 text-sm text-foreground shadow-sm transition-colors',
                    'focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30',
                    invalid ? 'border-destructive' : 'border-border',
                    className,
                )}
                {...props}
            >
                {children}
            </select>
            <ChevronDown
                className="pointer-events-none absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"
                strokeWidth={2}
                aria-hidden="true"
            />
        </div>
    ),
);

Select.displayName = 'Select';
