import { format } from 'date-fns';
import { id as idLocale } from 'react-day-picker/locale';
import { CalendarIcon } from 'lucide-react';
import * as React from 'react';

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

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;
        }

        if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value)) {
            const [year, month, day] = value.split('-').map(Number);
            return new Date(year, month - 1, day);
        }

        return new Date(value);
    }, [value]);

    const formattedDate = React.useMemo(() => {
        if (!date) {
return '';
}

        return format(date, 'dd MMM yyyy', { locale: idLocale });
    }, [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"
                    locale={idLocale}
                    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 };
