import { ChevronDownIcon } from "lucide-react";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Calendar } from "@/components/ui/calendar";
import {
	Popover,
	PopoverContent,
	PopoverTrigger,
} from "@/components/ui/popover";
import { Label } from "../../../components/ui/label";
import { useFieldContext } from "..";
import { FieldErrors } from "./FieldErrors";

type DateFieldProps = {
	label: string;
};
export const DateField = ({ label }: DateFieldProps) => {
	const field = useFieldContext<any>();
	const [open, setOpen] = useState(false);
	const date = field.state.value;

	return (
		<div className="grid gap-3">
			<Label htmlFor={field.name}>{label}</Label>
			<Popover open={open} onOpenChange={setOpen}>
				<PopoverTrigger asChild>
					<Button
						variant="outline"
						id="date"
						className="w-48 justify-between font-normal"
					>
						{date ? date.toLocaleDateString() : "Select date"}
						<ChevronDownIcon />
					</Button>
				</PopoverTrigger>
				<PopoverContent className="w-auto overflow-hidden p-0" align="start">
					<Calendar
						mode="single"
						selected={date}
						captionLayout="dropdown"
						startMonth={new Date(new Date().getFullYear() - 10, 0)}
						endMonth={new Date(new Date().getFullYear() + 20, 0)}
						onSelect={(selected) => {
							field.handleChange(selected ?? undefined);
							setOpen(false);
						}}
					/>
				</PopoverContent>
			</Popover>
			<FieldErrors meta={field.state.meta} />
		</div>
	);
};
