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

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

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

export const SelectField = ({
    label,
    options,
    placeholder,
}: 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)}
                >
                    <SelectTrigger
                        id={field.name}
                        onBlur={field.handleBlur}
                        className="w-[380px]"
                    >
                        <SelectValue placeholder={placeholder} />
                    </SelectTrigger>
                    <SelectContent>
                        {options.map((option) => (
                            <SelectItem key={option.value} value={option.value}>
                                {option.label}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
            </div>
            <FieldErrors meta={field.state.meta} />
        </div>
    );
};
