import { useState } from "react"
import { format, isBefore, parseISO, startOfDay, subDays } from "date-fns"

import { Button } from "@/components/ui/button"
import { Calendar } from "@/components/ui/calendar"
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from "@/components/ui/popover"
import { CalendarDays } from "lucide-react"
import { cn } from "@/lib/utils"

interface DatePickerProps {
    value?: string | null
    onChange?: (date: string) => void,
    className?: string
    disabled?: boolean
    disabledPrevies?: string
}

export default function DatePicker({ value, onChange, className, disabled, disabledPrevies }: DatePickerProps) {
    const [open, setOpen] = useState(false)

    function handleSelect(date: Date | undefined) {
        if (!date) return
        onChange?.(format(date, "yyyy-MM-dd"))
        setOpen(false)
    }



    return (
        <Popover open={open} onOpenChange={setOpen}>
            <PopoverTrigger asChild>
                <Button variant="outline" disabled={disabled} className={cn("w-full justify-between items-center", className)}>  {value ? format(value, "PPP") : "Select date"} <CalendarDays /></Button>
            </PopoverTrigger>

            <PopoverContent className="w-auto p-0">
                <Calendar
                    mode="single"
                    selected={value ? parseISO(value) : undefined}
                    onSelect={handleSelect}
                    disabled={(date) => isBefore(date, parseISO(disabledPrevies ?? format(new Date().toISOString(), "yyyy-MM-dd")))}
                />
            </PopoverContent>
        </Popover>
    )
}
