"use client";

import React from "react";
import { motion } from "framer-motion";
import { Button } from "../ui/button";
import { Calendar } from "../ui/calendar";
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
import { cn } from "../../lib/utils";
import { CalendarIcon, ChevronDown } from "lucide-react";
import {
    format,
    startOfDay,
    endOfDay,
    subDays,
    startOfWeek,
    endOfWeek,
    startOfMonth,
    endOfMonth,
} from "date-fns";
import { TimeRange } from "./types";

interface TimeRangePickerProps {
    value?: TimeRange;
    onChange?: (range: TimeRange) => void;
    className?: string;
    showPresets?: boolean;
    showComparison?: boolean;
    glassmorphism?: boolean;
}

const PRESET_RANGES = [
    {
        label: "Today",
        value: "today",
        getRange: () => ({
            start: startOfDay(new Date()),
            end: endOfDay(new Date()),
            label: "Today",
            preset: "today" as const,
        }),
    },
    {
        label: "Yesterday",
        value: "yesterday",
        getRange: () => ({
            start: startOfDay(subDays(new Date(), 1)),
            end: endOfDay(subDays(new Date(), 1)),
            label: "Yesterday",
            preset: "yesterday" as const,
        }),
    },
    {
        label: "Last 7 days",
        value: "last7days",
        getRange: () => ({
            start: startOfDay(subDays(new Date(), 6)),
            end: endOfDay(new Date()),
            label: "Last 7 days",
            preset: "last7days" as const,
        }),
    },
    {
        label: "Last 30 days",
        value: "last30days",
        getRange: () => ({
            start: startOfDay(subDays(new Date(), 29)),
            end: endOfDay(new Date()),
            label: "Last 30 days",
            preset: "last30days" as const,
        }),
    },
    {
        label: "This week",
        value: "thisWeek",
        getRange: () => ({
            start: startOfWeek(new Date()),
            end: endOfWeek(new Date()),
            label: "This week",
            preset: "custom" as const,
        }),
    },
    {
        label: "This month",
        value: "thisMonth",
        getRange: () => ({
            start: startOfMonth(new Date()),
            end: endOfMonth(new Date()),
            label: "This month",
            preset: "thisMonth" as const,
        }),
    },
    {
        label: "Last month",
        value: "lastMonth",
        getRange: () => {
            const lastMonth = subDays(startOfMonth(new Date()), 1);
            return {
                start: startOfMonth(lastMonth),
                end: endOfMonth(lastMonth),
                label: "Last month",
                preset: "lastMonth" as const,
            };
        },
    },
];

export function TimeRangePicker({
    value,
    onChange,
    className,
    showPresets = true,
    showComparison = false,
    glassmorphism = false,
}: TimeRangePickerProps) {
    const [isOpen, setIsOpen] = React.useState(false);
    const [customRange, setCustomRange] = React.useState<{
        from?: Date;
        to?: Date;
    }>({
        from: undefined,
        to: undefined,
    });
    const [comparisonEnabled, setComparisonEnabled] = React.useState(false);

    const currentRange = value || PRESET_RANGES[2].getRange(); // Default: Last 7 days

    // Format tarih aralığı
    const formatRange = (range: TimeRange) => {
        if (range.preset && range.preset !== "custom") {
            return range.label;
        }
        return `${format(range.start, "MMM d")} - ${format(range.end, "MMM d, yyyy")}`;
    };

    // Preset seçimi
    const handlePresetSelect = (preset: (typeof PRESET_RANGES)[0]) => {
        const range = preset.getRange();
        onChange?.(range);
        setIsOpen(false);
    };

    // Custom tarih seçimi
    const handleCustomRangeSelect = () => {
        if (customRange.from && customRange.to) {
            onChange?.({
                start: startOfDay(customRange.from),
                end: endOfDay(customRange.to),
                label: `${format(customRange.from, "MMM d")} - ${format(customRange.to, "MMM d, yyyy")}`,
                preset: "custom",
            });
            setIsOpen(false);
        }
    };

    return (
        <Popover open={isOpen} onOpenChange={setIsOpen}>
            <PopoverTrigger asChild>
                <Button
                    variant="outline"
                    className={cn(
                        "justify-start text-left font-normal",
                        glassmorphism &&
                            "bg-background/60 backdrop-blur-sm border-white/10",
                        !value && "text-muted-foreground",
                        className
                    )}
                >
                    <CalendarIcon className="mr-2 h-4 w-4" />
                    {formatRange(currentRange)}
                    <ChevronDown className="ml-auto h-4 w-4 opacity-50" />
                </Button>
            </PopoverTrigger>
            <PopoverContent
                className={cn(
                    "time-range-popover w-auto max-w-[95vw] sm:max-w-4xl p-0 overflow-hidden",
                    glassmorphism &&
                        "bg-background/95 backdrop-blur-md border-white/10"
                )}
                align="end"
                side="bottom"
                sideOffset={4}
                collisionPadding={16}
            >
                <motion.div
                    initial={{ opacity: 0, y: -10 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.2 }}
                    className="min-w-0"
                >
                    {/* Mobile: Stacked Layout */}
                    <div className="sm:hidden">
                        {/* Custom tarih seçici */}
                        <div className="p-3">
                            {/* Karşılaştırma */}
                            {showComparison && (
                                <div className="mt-3 pt-3 border-t">
                                    <label className="flex items-center gap-2 cursor-pointer">
                                        <input
                                            type="checkbox"
                                            checked={comparisonEnabled}
                                            onChange={(e) =>
                                                setComparisonEnabled(
                                                    e.target.checked
                                                )
                                            }
                                            className="rounded w-3 h-3"
                                        />
                                        <span className="text-xs">
                                            Compare to previous
                                        </span>
                                    </label>
                                </div>
                            )}
                        </div>
                    </div>

                    {/* Desktop: Side by Side Layout */}
                    <div className="hidden sm:flex">
                        {/* Preset'ler */}
                        {showPresets && (
                            <div className="preset-column border-r p-3 min-w-[140px]">
                                <div className="grid grid-cols-1 gap-1">
                                    {PRESET_RANGES.map((preset) => (
                                        <motion.button
                                            key={preset.value}
                                            whileHover={{ x: 2 }}
                                            whileTap={{ scale: 0.98 }}
                                            onClick={() =>
                                                handlePresetSelect(preset)
                                            }
                                            className={cn(
                                                "w-full text-left px-2 py-1.5 text-sm rounded-md transition-colors whitespace-nowrap",
                                                "hover:bg-muted",
                                                currentRange.preset ===
                                                    preset.value &&
                                                    "bg-primary text-primary-foreground"
                                            )}
                                        >
                                            {preset.label}
                                        </motion.button>
                                    ))}
                                </div>

                                {/* Karşılaştırma */}
                                {showComparison && (
                                    <div className="mt-4 pt-4 border-t">
                                        <label className="flex items-center gap-2 px-2 cursor-pointer">
                                            <input
                                                type="checkbox"
                                                checked={comparisonEnabled}
                                                onChange={(e) =>
                                                    setComparisonEnabled(
                                                        e.target.checked
                                                    )
                                                }
                                                className="rounded w-4 h-4"
                                            />
                                            <span className="text-sm">
                                                Compare to previous period
                                            </span>
                                        </label>
                                    </div>
                                )}
                            </div>
                        )}

                        {/* Custom tarih seçici */}
                        <div className="p-3 flex-1">
                            <div className="overflow-x-auto">
                                <Calendar
                                    mode="range"
                                    selected={{
                                        from: customRange.from,
                                        to: customRange.to,
                                    }}
                                    onSelect={(range: any) =>
                                        setCustomRange(
                                            range || {
                                                from: undefined,
                                                to: undefined,
                                            }
                                        )
                                    }
                                    numberOfMonths={2}
                                    showOutsideDays={true}
                                    className="rounded-md"
                                />
                            </div>

                            <div className="flex items-center justify-between pt-3 px-2">
                                <div className="text-sm text-muted-foreground">
                                    {customRange.from && customRange.to && (
                                        <span>
                                            {Math.ceil(
                                                (customRange.to.getTime() -
                                                    customRange.from.getTime()) /
                                                    (1000 * 60 * 60 * 24)
                                            )}{" "}
                                            days selected
                                        </span>
                                    )}
                                </div>
                                <div className="flex gap-2">
                                    <Button
                                        variant="ghost"
                                        size="sm"
                                        onClick={() => {
                                            setCustomRange({
                                                from: undefined,
                                                to: undefined,
                                            });
                                            setIsOpen(false);
                                        }}
                                    >
                                        Cancel
                                    </Button>
                                    <Button
                                        size="sm"
                                        onClick={handleCustomRangeSelect}
                                        disabled={
                                            !customRange.from || !customRange.to
                                        }
                                    >
                                        Apply
                                    </Button>
                                </div>
                            </div>
                        </div>
                    </div>
                </motion.div>
            </PopoverContent>
        </Popover>
    );
}

export default TimeRangePicker;
