import { Label } from "../../components/ui/label";
import {
	Select,
	SelectContent,
	SelectItem,
	SelectTrigger,
	SelectValue,
} from "../../components/ui/select";
import { useFieldContext } from ".";
import { FieldErrors } from "./Errors.Field";

type SelectOption = {
	value: string;
	label: string;
};

type SelectFieldProps = {
	label: string;
	options: SelectOption[];
	placeholder?: string;
	disabled?: boolean;
};

export const SelectField = ({
	label,
	options,
	placeholder,
	disabled = false,
}: SelectFieldProps) => {
	const field = useFieldContext<string>();

	return (
		<div className="grid gap-3">
			<div className="grid gap-3">
				<Label htmlFor={field.name}>{label}</Label>
				<Select
					value={field.state.value}
					onValueChange={(value) => field.handleChange(value)}
					disabled={disabled}
				>
					<SelectTrigger
						id={field.name}
						onBlur={field.handleBlur}
						className="w-min-2/3 w-max-fit"
					>
						<SelectValue placeholder={placeholder} />
					</SelectTrigger>
					<SelectContent position={"popper"}>
						{options.map((option) => (
							<SelectItem key={option.value} value={option.value}>
								{option.label}
							</SelectItem>
						))}
					</SelectContent>
				</Select>
			</div>
			<FieldErrors meta={field.state.meta} />
		</div>
	);
};
