import { Button, Input } from '@repo/shadcn-ui/components';
import { cn } from "@repo/shadcn-ui/lib/utils";
// DateInputField.tsx
import { CalendarIcon, LockIcon, XIcon } from "lucide-react";

export function DateInputField({
    id,
    value,
    onChange,
    onBlurConfirm,
    onClear,
    placeholder,
    disabled,
    readOnly,
    required,
    hasError,
    describedBy,
    onOpenRequest,
    triggerButton, // ← PopoverTrigger se inyecta aquí
}: {
    id: string;
    value: string;
    onChange: (val: string) => void;
    onBlurConfirm: () => void; // valida+normaliza en blur/Enter
    onClear: () => void;
    placeholder?: string;
    disabled: boolean;
    readOnly: boolean;
    required: boolean;
    hasError: boolean;
    describedBy?: string;
    onOpenRequest?: () => void;
    triggerButton?: React.ReactNode;
}) {
    return (
        <div className="relative">
            <Input
                id={id}
                type="text"
                pattern="\d{2}/\d{2}/\d{4}"
                value={value}
                onChange={(e) => onChange(e.target.value)}
                onBlur={onBlurConfirm}
                onKeyDown={(e) => {
                    if (e.key === "Enter") {
                        e.preventDefault();
                        onBlurConfirm();
                    }
                    if ((e.altKey || e.metaKey) && e.key === "ArrowDown") {
                        onOpenRequest?.();
                    }
                }}
                readOnly={readOnly}
                disabled={disabled}
                aria-invalid={hasError || undefined}
                aria-describedby={describedBy}
                className={cn(
                    "text-ellipsis pr-12",
                    disabled && "bg-muted text-muted-foreground cursor-not-allowed",
                    readOnly && "bg-muted text-foreground cursor-default",
                    !disabled && !readOnly && "bg-white text-foreground",
                    hasError && "border-destructive ring-destructive"
                )}
                placeholder={placeholder}
            />
            <div className="absolute inset-y-0 right-2 flex items-center gap-2 pr-1">
                {!readOnly && !required && value && (
                    <Button
                        variant={'link'}
                        type='button'
                        size={"icon-sm"}
                        onClick={onClear}
                        aria-label="Clear date"
                        className="text-muted-foreground hover:text-destructive transition cursor-pointer -mr-3"
                    >
                        <XIcon className="size-4" />
                    </Button>
                )}
                {readOnly ? (
                    <LockIcon className="size-4" />
                ) : (
                    triggerButton ?? <CalendarIcon className="size-4" aria-hidden="true" />
                )}
            </div>
        </div>
    );
}
