import { Calendar, FormControl, FormField, FormItem, FormLabel, FormMessage, Popover, PopoverContent, PopoverTrigger, } from "@repo/shadcn-ui/components"; import { CalendarIcon, LockIcon, XIcon } from "lucide-react"; import { cn } from "@repo/shadcn-ui/lib/utils"; import { format, isValid, parse } from "date-fns"; import { useState } from "react"; import { Control, FieldPath, FieldValues } from "react-hook-form"; import { useTranslation } from "../../locales/i18n.ts"; type DatePickerInputFieldProps = { control: Control; name: FieldPath; label: string; placeholder?: string; description?: string; disabled?: boolean; required?: boolean; readOnly?: boolean; className?: string; formatDateFn?: (iso: string) => string; parseDateFormat?: string; // e.g. "dd/MM/yyyy" }; export function DatePickerInputField({ control, name, label, placeholder, description, disabled = false, required = false, readOnly = false, className, formatDateFn = (iso) => format(new Date(iso), "dd/MM/yyyy"), parseDateFormat = "dd/MM/yyyy", }: DatePickerInputFieldProps) { const { t } = useTranslation(); const isDisabled = disabled; const isReadOnly = readOnly && !disabled; return ( { const [inputValue, setInputValue] = useState( field.value ? formatDateFn(field.value) : "" ); const [inputError, setInputError] = useState(null); const handleInputChange = (value: string) => { setInputValue(value); setInputError(null); }; const validateAndSetDate = () => { const trimmed = inputValue.trim(); if (!trimmed) { field.onChange(undefined); setInputError(null); return; } const parsed = parse(trimmed, parseDateFormat, new Date()); if (isValid(parsed)) { field.onChange(parsed.toISOString()); setInputError(null); } else { setInputError(t("common.invalidDate") || "Fecha no vĂ¡lida"); } }; return (
{label} {required && {t("common.required")}}
handleInputChange(e.target.value)} onBlur={validateAndSetDate} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); validateAndSetDate(); } }} readOnly={isReadOnly} disabled={isDisabled} className={cn( "w-full rounded-md border px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-2 focus:ring-ring", isDisabled && "bg-muted text-muted-foreground cursor-not-allowed", isReadOnly && "bg-muted text-foreground cursor-default", !isDisabled && !isReadOnly && "bg-white text-foreground", inputError && "border-destructive ring-destructive" )} placeholder={placeholder} />
{!isReadOnly && !required && inputValue && ( )} {isReadOnly ? ( ) : ( )}
{!isDisabled && !isReadOnly && ( { if (date) { const iso = date.toISOString(); field.onChange(iso); setInputValue(formatDateFn(iso)); setInputError(null); } else { field.onChange(undefined); setInputValue(""); } }} initialFocus /> )}
{isReadOnly && (

{t("common.readOnly") || "Solo lectura"}

)} {(inputError || description) && (

{inputError || description}

)}
); }} /> ); }