import * as React from "react";
import { format, subDays } from "date-fns";
import { ptBR } from "date-fns/locale";
import { CalendarIcon } from "lucide-react";

import { cn } from "@/lib/utils";
import { Button } from "@/Components/ui/button";
import { Calendar } from "@/Components/ui/calendar";
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from "@/Components/ui/popover";

export function DatePicker({ value, onChange, placeholder = "Selecione a data", disabled, className, minDate, maxDate }) {
    const date = value ? new Date(value + "T12:00:00") : undefined;

    function handleSelect(day) {
        if (day) {
            const iso = format(day, "yyyy-MM-dd");
            onChange(iso);
        }
    }

    // D-1: fallback para ontem quando maxDate nao e informado
    const disabledMatcher = [];
    if (maxDate) disabledMatcher.push({ after: new Date(maxDate + "T12:00:00") });
    else disabledMatcher.push({ after: subDays(new Date(), 1) });
    if (minDate) disabledMatcher.push({ before: new Date(minDate + "T12:00:00") });

    return (
        <Popover>
            <PopoverTrigger asChild>
                <Button
                    variant="outline"
                    disabled={disabled}
                    className={cn(
                        "w-full justify-start text-left font-normal",
                        !date && "text-muted-foreground",
                        className
                    )}
                >
                    <CalendarIcon className="mr-2 h-4 w-4" />
                    {date ? format(date, "dd/MM/yyyy") : placeholder}
                </Button>
            </PopoverTrigger>
            <PopoverContent className="w-auto p-0" align="start">
                <Calendar
                    mode="single"
                    selected={date}
                    onSelect={handleSelect}
                    locale={ptBR}
                    disabled={disabledMatcher}
                    defaultMonth={date}
                />
            </PopoverContent>
        </Popover>
    );
}
