import { format } from 'date-fns';
import { CalendarDays } from 'lucide-react';
import { useState } from 'react';
import type { DateRange } from 'react-day-picker';
import { ReportsExportMenu } from '@/components/reporting/reports-export-menu';
import { Button } from '@/components/ui/button';
import { Calendar } from '@/components/ui/calendar';
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from '@/components/ui/popover';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';

type RangeOption = {
    value: string;
    label: string;
};

type ReportsActionBarProps = {
    activeRange: string;
    rangeOptions: RangeOption[];
    onRangeChange: (value: string) => void;
    customRange: {
        from: Date | undefined;
        to: Date | undefined;
    };
    onCustomRangeApply: (range: DateRange) => void;
    onDownloadPdfSummary: () => void;
    onDownloadExcel: () => void;
    onExportRawCsv: () => void;
};

export function ReportsActionBar({
    activeRange,
    rangeOptions,
    onRangeChange,
    customRange,
    onCustomRangeApply,
    onDownloadPdfSummary,
    onDownloadExcel,
    onExportRawCsv,
}: ReportsActionBarProps) {
    const [pickerOpen, setPickerOpen] = useState(false);
    const [draftRange, setDraftRange] = useState<DateRange>({
        from: customRange.from,
        to: customRange.to,
    });

    const visibleRange = pickerOpen ? draftRange : customRange;
    const rangeLabel = visibleRange.from
        ? visibleRange.to
            ? `${format(visibleRange.from, 'MMM d, yyyy')} - ${format(visibleRange.to, 'MMM d, yyyy')}`
            : format(visibleRange.from, 'MMM d, yyyy')
        : 'Select range';

    const handlePickerOpenChange = (open: boolean) => {
        if (open) {
            setDraftRange({
                from: customRange.from,
                to: customRange.to,
            });
        }

        setPickerOpen(open);
    };

    return (
        <div className="sticky top-4 z-20 ml-auto flex w-full max-w-3xl items-center justify-end gap-2 rounded-lg bg-background/90 p-2 backdrop-blur-sm">
            <Select value={activeRange} onValueChange={onRangeChange}>
                <SelectTrigger className="w-40" size="sm">
                    <SelectValue placeholder="Last 30 Days" />
                </SelectTrigger>
                <SelectContent>
                    {rangeOptions.map((option) => (
                        <SelectItem key={option.value} value={option.value}>
                            {option.label}
                        </SelectItem>
                    ))}
                </SelectContent>
            </Select>
            <Popover open={pickerOpen} onOpenChange={handlePickerOpenChange}>
                <PopoverTrigger asChild>
                    <Button
                        variant="outline"
                        size="sm"
                        className="w-[280px] justify-start text-left font-normal"
                    >
                        <CalendarDays className="size-4" />
                        {rangeLabel}
                    </Button>
                </PopoverTrigger>
                <PopoverContent align="end" className="w-auto p-0">
                    <Calendar
                        mode="range"
                        numberOfMonths={2}
                        resetOnSelect
                        selected={draftRange.from ? draftRange : undefined}
                        onSelect={(range) =>
                            setDraftRange(
                                range ?? { from: undefined, to: undefined },
                            )
                        }
                        defaultMonth={draftRange.from ?? new Date()}
                    />
                    <div className="flex items-center justify-end gap-2 border-t p-3">
                        <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                                setDraftRange({
                                    from: undefined,
                                    to: undefined,
                                });
                            }}
                        >
                            Clear
                        </Button>
                        <Button
                            size="sm"
                            disabled={!draftRange.from || !draftRange.to}
                            onClick={() => {
                                if (!draftRange.from || !draftRange.to) {
                                    return;
                                }

                                onCustomRangeApply(draftRange);
                                setPickerOpen(false);
                            }}
                        >
                            Apply
                        </Button>
                    </div>
                </PopoverContent>
            </Popover>
            <ReportsExportMenu
                onDownloadPdfSummary={onDownloadPdfSummary}
                onDownloadExcel={onDownloadExcel}
                onExportRawCsv={onExportRawCsv}
            />
        </div>
    );
}
