"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { CalendarIcon } from "lucide-react";
import { cn } from "@open-mercato/shared/lib/utils";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Popover, PopoverContent, PopoverTrigger } from "./popover.js";
import { Calendar } from "./calendar.js";
import { Button } from "./button.js";
import {
  defaultDateRangePresets
} from "./date-picker-helpers.js";
import { formatWithPublicDateFormat, resolvePublicDateFormat } from "./date-format.js";
function defaultFormatRange(range, locale) {
  const fmt = resolvePublicDateFormat(locale);
  return `${formatWithPublicDateFormat(range.start, fmt, locale) ?? ""} \u2013 ${formatWithPublicDateFormat(range.end, fmt, locale) ?? ""}`;
}
function toRDPRange(range) {
  if (!range) return void 0;
  return { from: range.start, to: range.end };
}
function fromRDPRange(rdp) {
  if (!rdp || !rdp.from) return null;
  return { start: rdp.from, end: rdp.to ?? rdp.from };
}
function rangesEqual(a, b) {
  if (!a && !b) return true;
  if (!a || !b) return false;
  return a.start.getTime() === b.start.getTime() && a.end.getTime() === b.end.getTime();
}
function DateRangePicker({
  value,
  onChange,
  presets,
  showPresets = true,
  placeholder,
  size = "default",
  disabled = false,
  readOnly = false,
  withFooter = true,
  align = "start",
  minDate,
  maxDate,
  numberOfMonths = 2,
  locale,
  formatRange,
  className,
  popoverClassName,
  id,
  name,
  required,
  "aria-label": ariaLabel,
  "aria-describedby": ariaDescribedBy
}) {
  const t = useT();
  const [open, setOpen] = React.useState(false);
  const [draft, setDraft] = React.useState(value ?? null);
  const [activePresetId, setActivePresetId] = React.useState(null);
  const isInteractive = !disabled && !readOnly;
  const useDraft = withFooter;
  React.useEffect(() => {
    if (open) {
      setDraft(value ?? null);
      setActivePresetId(null);
    }
  }, [open, value]);
  const resolvedPresets = React.useMemo(
    () => presets ?? defaultDateRangePresets(),
    [presets]
  );
  const placeholderText = placeholder ?? t("ui.dateRangePicker.placeholder", "Pick a date range");
  const formatter = formatRange ?? defaultFormatRange;
  const formattedValue = React.useMemo(() => {
    if (!value) return null;
    return formatter(value, locale);
  }, [value, formatter, locale]);
  const selectedDate = useDraft ? draft : value;
  const rdpSelected = toRDPRange(selectedDate);
  const handleRangeSelect = React.useCallback(
    (rdpRange) => {
      if (!isInteractive) return;
      const next = fromRDPRange(rdpRange);
      setActivePresetId(null);
      if (useDraft) {
        setDraft(next);
      } else {
        onChange(next);
        if (next?.start && next?.end) setOpen(false);
      }
    },
    [isInteractive, useDraft, onChange]
  );
  const handlePresetClick = React.useCallback(
    (preset) => {
      if (!isInteractive) return;
      const range = preset.range();
      setActivePresetId(preset.id);
      if (useDraft) {
        setDraft(range);
      } else {
        onChange(range);
        setOpen(false);
      }
    },
    [isInteractive, useDraft, onChange]
  );
  const handleApply = React.useCallback(() => {
    onChange(draft);
    setOpen(false);
  }, [draft, onChange]);
  const handleCancel = React.useCallback(() => {
    setDraft(value ?? null);
    setActivePresetId(null);
    setOpen(false);
  }, [value]);
  const disabledMatcher = React.useMemo(() => {
    if (!minDate && !maxDate) return void 0;
    const matchers = [];
    if (minDate) matchers.push({ before: minDate });
    if (maxDate) matchers.push({ after: maxDate });
    return matchers;
  }, [minDate, maxDate]);
  const heightClass = size === "sm" ? "h-8 px-2.5 text-xs" : "h-9 px-3 text-sm";
  return /* @__PURE__ */ jsxs(Popover, { open, onOpenChange: isInteractive ? setOpen : void 0, children: [
    /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
      "button",
      {
        type: "button",
        id,
        name,
        "aria-label": ariaLabel,
        "aria-describedby": ariaDescribedBy,
        "aria-haspopup": "dialog",
        "aria-required": required ? true : void 0,
        "data-crud-focus-target": "",
        "data-slot": "date-range-picker-trigger",
        disabled,
        className: cn(
          "w-full inline-flex items-center gap-2 rounded-md border border-input bg-background shadow-xs transition-colors text-left",
          "focus-visible:outline-none focus-visible:shadow-focus focus-visible:border-foreground",
          "hover:bg-muted/40",
          "disabled:bg-bg-disabled disabled:border-border-disabled disabled:shadow-none disabled:hover:bg-bg-disabled disabled:cursor-not-allowed",
          "aria-invalid:border-destructive",
          heightClass,
          readOnly && "cursor-default opacity-70",
          !formattedValue && "text-muted-foreground",
          className
        ),
        onClick: isInteractive ? void 0 : (event) => event.preventDefault(),
        children: [
          /* @__PURE__ */ jsx(CalendarIcon, { className: "h-4 w-4 shrink-0 text-muted-foreground", "aria-hidden": "true" }),
          /* @__PURE__ */ jsx("span", { className: "flex-1 truncate", children: formattedValue ?? placeholderText })
        ]
      }
    ) }),
    /* @__PURE__ */ jsxs(
      PopoverContent,
      {
        align,
        className: cn(
          "w-auto p-0 flex flex-col overflow-hidden",
          "max-h-[var(--radix-popover-content-available-height)]",
          popoverClassName
        ),
        children: [
          /* @__PURE__ */ jsxs("div", { className: "flex min-h-0 flex-1 overflow-auto", children: [
            showPresets ? /* @__PURE__ */ jsx(
              "div",
              {
                "data-slot": "date-range-presets",
                className: "flex w-[200px] shrink-0 flex-col gap-0.5 overflow-y-auto border-r p-2",
                children: resolvedPresets.map((preset) => {
                  const isActive = activePresetId === preset.id;
                  return /* @__PURE__ */ jsx(
                    "button",
                    {
                      type: "button",
                      onClick: () => handlePresetClick(preset),
                      className: cn(
                        "inline-flex h-8 items-center rounded-md px-3 text-left text-sm transition-colors shrink-0",
                        "hover:bg-accent hover:text-accent-foreground",
                        "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
                        isActive && "bg-muted font-medium text-foreground"
                      ),
                      children: t(preset.labelKey, preset.id.replace(/_/g, " "))
                    },
                    preset.id
                  );
                })
              }
            ) : null,
            /* @__PURE__ */ jsx("div", { className: "p-3", children: /* @__PURE__ */ jsx(
              Calendar,
              {
                mode: "range",
                selected: rdpSelected,
                onSelect: handleRangeSelect,
                locale,
                disabled: disabledMatcher,
                numberOfMonths,
                autoFocus: true
              }
            ) })
          ] }),
          withFooter ? /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center justify-between gap-3 border-t bg-popover px-3 py-2", children: [
            /* @__PURE__ */ jsx("span", { className: "truncate text-xs text-muted-foreground", children: selectedDate ? `${t("ui.dateRangePicker.rangeLabel", "Range")}: ${formatter(selectedDate, locale)}` : t("ui.dateRangePicker.rangeEmpty", "No range selected") }),
            /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center gap-2", children: [
              /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "sm", onClick: handleCancel, children: t("ui.dateRangePicker.cancelButton", "Cancel") }),
              /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", onClick: handleApply, children: t("ui.dateRangePicker.applyButton", "Apply") })
            ] })
          ] }) : null
        ]
      }
    )
  ] });
}
export {
  DateRangePicker
};
//# sourceMappingURL=date-range-picker.js.map
