import { Check, ChevronsUpDown } from "lucide-react";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
	Command,
	CommandEmpty,
	CommandGroup,
	CommandInput,
	CommandItem,
	CommandList,
} from "@/components/ui/command";
import {
	Popover,
	PopoverContent,
	PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { Label } from "../../../components/ui/label";
import { useFieldContext } from "..";
import { FieldErrors } from "./FieldErrors";

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

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

export const Searchable = ({ label, options, searchFor }: SelectFieldProps) => {
	const field = useFieldContext<string>();
	const [open, setOpen] = useState(false);

	return (
		<div className="grid gap-3">
			<div className="grid gap-3">
				<Label htmlFor={field.name}>{label}</Label>
				<Popover open={open} onOpenChange={setOpen}>
					<PopoverTrigger asChild>
						<Button
							variant="outline"
							role="combobox"
							aria-expanded={open}
							className="w-[200px] justify-between"
						>
							{field.state.value
								? options.find((options) => options.value === field.state.value)
										?.label
								: `Search ${searchFor}...`}
							<ChevronsUpDown className="opacity-50" />
						</Button>
					</PopoverTrigger>
					<PopoverContent className="w-[200px] p-0">
						<Command>
							<CommandInput
								placeholder={`Search ${searchFor}...`}
								className="h-9"
							/>
							<CommandList>
								<CommandEmpty>{`No ${searchFor} found.`}</CommandEmpty>
								<CommandGroup>
									{options.map((options) => (
										<CommandItem
											key={options.value}
											value={options.value}
											onSelect={(currentValue) => {
												field.handleChange(
													currentValue === field.state.value
														? ""
														: currentValue,
												);
												setOpen(false);
											}}
										>
											{options.label}
											<Check
												className={cn(
													"ml-auto",
													field.state.value === options.value
														? "opacity-100"
														: "opacity-0",
												)}
											/>
										</CommandItem>
									))}
								</CommandGroup>
							</CommandList>
						</Command>
					</PopoverContent>
				</Popover>
			</div>
			<FieldErrors meta={field.state.meta} />
		</div>
	);
};
