import TextInput from '@/Components/TextInput';
import { Button } from '@/Components/ui/button';
import { Calendar } from '@/Components/ui/calendar';
import { PopoverContent } from '@/Components/ui/popover';
import { cn } from '@/lib/utils';
import { Popover, PopoverTrigger } from '@radix-ui/react-popover';
import { Dayjs } from 'dayjs';

interface DateInputProps {
    date?: Dayjs | null;
    onSelect: (date: Date) => void;
    disabledFuture?: boolean;
    disabledPast?: boolean;
    readOnly?: boolean;
}

export default function DateInput({
    date,
    onSelect,
    disabledFuture = false,
    disabledPast = false,
    readOnly,
}: DateInputProps) {
    const fromDate = disabledPast ? new Date() : new Date(1900, 1);
    const toDate = disabledFuture ? new Date() : new Date(3000, 1);

    if (readOnly) {
        return (
            <TextInput readOnly value={date ? date.format('DD/MM/YYYY') : ''} />
        );
    }
    return (
        <Popover>
            <PopoverTrigger asChild>
                <Button
                    variant={'outline'}
                    className={cn(
                        'min-w-[120px] justify-start rounded-md text-left font-normal',
                        !date && 'text-muted-foreground',
                    )}
                >
                    {date ? date.format('DD/MM/YYYY') : ''}
                </Button>
            </PopoverTrigger>
            <PopoverContent className="w-auto p-0" align="start">
                <Calendar
                    captionLayout="dropdown-buttons"
                    fromDate={fromDate}
                    toDate={toDate}
                    mode="single"
                    selected={date ? date.toDate() : undefined}
                    onSelect={(day) => {
                        if (day) {
                            onSelect(day);
                        }
                    }}
                    initialFocus
                />
            </PopoverContent>
        </Popover>
    );
}
