import * as React from "react";
import { format } from "date-fns";
import { CalendarIcon, X } from "lucide-react";
import type { DateRange as CalendarDateRange } from "react-day-picker";

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";
import { Badge } from "@/components/ui/badge";

export interface DateRange {
  from?: Date;
  to?: Date;
}

export interface DateRangePickerProps {
  value?: DateRange;
  onChange?: (range: DateRange | undefined) => void;
  placeholder?: string;
  disabled?: boolean;
  className?: string;
  disableFuture?: boolean;
  disablePast?: boolean;
  fromYear?: number;
  toYear?: number;
  presets?: Array<{
    label: string;
    range: DateRange;
  }>;
}

const defaultPresets = [
  {
    label: "Today",
    range: {
      from: new Date(),
      to: new Date(),
    },
  },
  {
    label: "Last 7 days",
    range: {
      from: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
      to: new Date(),
    },
  },
  {
    label: "Last 30 days",
    range: {
      from: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
      to: new Date(),
    },
  },
  {
    label: "This year",
    range: {
      from: new Date(new Date().getFullYear(), 0, 1),
      to: new Date(),
    },
  },
];

export function DateRangePicker({
  value,
  onChange,
  placeholder = "Pick a date range",
  disabled = false,
  className,
  disableFuture = false,
  disablePast = false,
  fromYear,
  toYear,
  presets = defaultPresets,
}: DateRangePickerProps) {
  const [open, setOpen] = React.useState(false);

  const handleSelect = (range: DateRange | undefined) => {
    onChange?.(range);
  };

  const handlePresetSelect = (preset: DateRange) => {
    handleSelect(preset);
    setOpen(false);
  };

  const handleClear = () => {
    handleSelect(undefined);
  };

  const getDisabledDates = (date: Date) => {
    const now = new Date();
    if (disableFuture && date > now) return true;
    if (disablePast && date < now) return true;
    return false;
  };

  const formatRange = (range: DateRange | undefined) => {
    if (!range?.from) return placeholder;
    if (!range.to) return format(range.from, "MMM dd, yyyy");
    if (range.from.getTime() === range.to.getTime()) {
      return format(range.from, "MMM dd, yyyy");
    }
    return `${format(range.from, "MMM dd, yyyy")} - ${format(range.to, "MMM dd, yyyy")}`;
  };

  return (
    <div className={cn("grid gap-2", className)}>
      <Popover open={open} onOpenChange={setOpen}>
        <PopoverTrigger asChild>
          <Button
            variant="outline"
            className={cn(
              "w-full justify-start text-left font-normal",
              !value?.from && "text-muted-foreground"
            )}
            disabled={disabled}
          >
            <CalendarIcon className="mr-2 h-4 w-4" />
            <span className="truncate flex-1">
              {formatRange(value)}
            </span>
            {value?.from && (
              <X
                className="ml-2 h-4 w-4 hover:text-destructive"
                onClick={(e) => {
                  e.stopPropagation();
                  handleClear();
                }}
              />
            )}
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-auto p-0" align="start">
          <div className="flex">
            <div className="flex flex-col sm:flex-row">
              <Calendar
                initialFocus
                mode="range"
                defaultMonth={value?.from}
                selected={value as CalendarDateRange}
                onSelect={handleSelect as (range: CalendarDateRange | undefined) => void}
                numberOfMonths={2}
                disabled={getDisabledDates}
                className="p-3 pointer-events-auto"
                fromYear={fromYear}
                toYear={toYear}
              />
            </div>
            {presets.length > 0 && (
              <div className="flex flex-col gap-2 border-l p-3">
                <div className="text-sm font-medium text-foreground">Presets</div>
                <div className="grid gap-1">
                  {presets.map((preset, index) => (
                    <Button
                      key={index}
                      variant="ghost"
                      size="sm"
                      className="justify-start text-left h-auto p-2"
                      onClick={() => handlePresetSelect(preset.range)}
                    >
                      {preset.label}
                    </Button>
                  ))}
                </div>
              </div>
            )}
          </div>
        </PopoverContent>
      </Popover>
      {value?.from && (
        <Badge variant="secondary" className="w-fit">
          {formatRange(value)}
        </Badge>
      )}
    </div>
  );
}