import { Link } from '@inertiajs/react';
import { create as purchaseProductsCreate } from '@/actions/App/Http/Controllers/PurchaseProductController';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { cn } from '@/lib/utils';

/**
 * @param {object} props
 * @param {Array<{id: number, name: string, unit_name?: string|null, is_active?: boolean}>} props.products
 * @param {string|number} props.value
 * @param {(value: string) => void} props.onValueChange
 * @param {Record<string, string>} props.labels
 * @param {string} [props.error]
 * @param {string} [props.id]
 */
export function PurchaseProductSelect({
    products = [],
    value,
    onValueChange,
    labels,
    error,
    id = 'purchase_product_id',
}) {
    const selectValue = value != null && value !== '' ? String(value) : '';

    if (products.length === 0) {
        return (
            <div className="space-y-2">
                <Label htmlFor={id}>{labels.product}</Label>
                <p className="text-muted-foreground text-sm">{labels.noProductsHint}</p>
                <Link
                    href={purchaseProductsCreate.url()}
                    className="text-primary text-sm font-medium underline-offset-4 hover:underline"
                >
                    {labels.addProductLink}
                </Link>
            </div>
        );
    }

    return (
        <div className="space-y-2">
            <Label htmlFor={id}>{labels.product}</Label>
            <Select value={selectValue} onValueChange={onValueChange}>
                <SelectTrigger
                    id={id}
                    aria-invalid={Boolean(error)}
                    className={cn(error && 'border-destructive')}
                >
                    <SelectValue placeholder={labels.productPlaceholder} />
                </SelectTrigger>
                <SelectContent>
                    {products.map((item) => (
                        <SelectItem key={item.id} value={String(item.id)}>
                            {item.name}
                            {item.unit_name ? ` (${item.unit_name})` : ''}
                            {item.is_active === false ? ` (${labels.productInactive})` : ''}
                        </SelectItem>
                    ))}
                </SelectContent>
            </Select>
            {error ? <p className="text-destructive text-sm">{error}</p> : null}
        </div>
    );
}
