import * as React from "react"
import { format } from "date-fns"
import { id } 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"

interface DatePickerProps {
    value?: Date | string | null
    onChange?: (date: Date | undefined) => void
    placeholder?: string
    disabled?: boolean
    className?: string
    name?: string
    id?: string
    min?: Date
    max?: Date
}

function DatePicker({
    value,
    onChange,
    placeholder = "Pilih tanggal",
    disabled = false,
    className,
    name,
    id,
    min,
    max,
}: DatePickerProps) {
    const [open, setOpen] = React.useState(false)

    const date = React.useMemo(() => {
        if (!value) return undefined
        if (value instanceof Date) return value
        return new Date(value)
    }, [value])

    const formattedDate = React.useMemo(() => {
        if (!date) return ""
        return format(date, "dd MMM yyyy", { locale: id })
    }, [date])

    return (
        <Popover open={open} onOpenChange={setOpen}>
            <PopoverTrigger asChild>
                <Button
                    id={id}
                    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 ? formattedDate : placeholder}
                </Button>
            </PopoverTrigger>
            <PopoverContent className="w-auto p-0" align="start">
                <Calendar
                    mode="single"
                    selected={date}
                    onSelect={(selectedDate) => {
                        onChange?.(selectedDate)
                        setOpen(false)
                    }}
                    disabled={(date) => {
                        if (min && date < min) return true
                        if (max && date > max) return true
                        return false
                    }}
                    initialFocus
                />
            </PopoverContent>
            {name && (
                <input type="hidden" name={name} value={date ? format(date, "yyyy-MM-dd") : ""} />
            )}
        </Popover>
    )
}

export { DatePicker }
