<script lang="ts">
	import Label from './Label.svelte';
	import { validate } from '@repo/validate';

	let {
		name,
		label,
		value = $bindable(''),
		required,
		missingMessage,
		node = $bindable(),
		options,
		placeholder
	}: {
		name: string;
		label?: string;
		value?: string;
		placeholder?: string;
		required?: boolean;
		missingMessage?: string;
		node?: HTMLSelectElement;
		options: {
			label: string;
			value: string;
		}[];
	} = $props();

	let valid: boolean = $state(true);
</script>

<div>
	<Label for={name}>{label}</Label>
	<select
		id={name}
		{name}
		bind:value
		class={[
			'border-accent w-full rounded-sm border bg-white px-[1.125rem] py-3.5 font-normal transition-colors',
			'text-text placeholder:text-text/60 dark:border-accent/50 dark:bg-text-800 placeholder:font-normal',
			'dark:text-background dark:placeholder:text-background/60 dark:sm:bg-slate-800',
			!valid && 'border-red-500!'
		]}
		use:validate={{ required }}
		onvalidate={(e) => {
			valid = e.detail.valid;
		}}
		bind:this={node}
	>
		{#if placeholder}
			<option value="" disabled selected={value === '' || value === undefined}>
				{placeholder}
			</option>
		{/if}
		{#each options as opt}
			<option value={opt.value} selected={opt.value === value}>
				{opt.label}
			</option>
		{/each}
	</select>

	<div class={['opacity-0 transition-opacity', !valid && 'opacity-100']}>
		<Label for={name} error>
			{missingMessage !== undefined && missingMessage !== '' ? missingMessage : 'Field is required'}
		</Label>
	</div>
</div>
