import * as React from 'react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';

export type CrmSelectChangeEvent = { target: { value: string } };

type Props = React.SelectHTMLAttributes<HTMLSelectElement> & {
    onChange?: (event: CrmSelectChangeEvent) => void;
};

/**
 * Shared CRM select field backed by the shadcn Select primitives.
 * It intentionally keeps the familiar value/onChange API so existing forms stay simple.
 */
export function CrmSelect({ value, defaultValue, onChange, children, className, disabled }: Props) {
    const EMPTY = '__crm_empty__';
    const current = value === '' || value == null ? EMPTY : String(value);
    const initial = defaultValue === '' || defaultValue == null ? EMPTY : String(defaultValue);
    const options = React.Children.toArray(children).filter(React.isValidElement) as React.ReactElement<React.OptionHTMLAttributes<HTMLOptionElement>>[];

    return (
        <Select
            value={current}
            defaultValue={value === undefined ? initial : undefined}
            disabled={disabled}
            onValueChange={(next) => onChange?.({ target: { value: next === EMPTY ? '' : next } })}
        >
            <SelectTrigger className={className} disabled={disabled}>
                <SelectValue placeholder={options.find((option) => option.props.value === '')?.props.children ?? 'Pilih'} />
            </SelectTrigger>
            <SelectContent>
                {options.map((option, index) => {
                    const optionValue = option.props.value === '' || option.props.value == null ? EMPTY : String(option.props.value);
                    return (
                        <SelectItem key={option.key ?? `${optionValue}-${index}`} value={optionValue}>
                            {option.props.children}
                        </SelectItem>
                    );
                })}
            </SelectContent>
        </Select>
    );
}
