"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 { LinkButton } from "./link-button.js";
import { TimeInput } from "../backend/inputs/TimeInput.js";
import { formatWithPublicDateFormat, resolvePublicDateFormat, resolvePublicDateTimeFormat } from "./date-format.js";
function extractTime(date) {
  return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
}
function applyTimeToDate(base, time) {
  const [hourStr = "0", minuteStr = "0"] = time.split(":");
  const hour = parseInt(hourStr, 10);
  const minute = parseInt(minuteStr, 10);
  const next = new Date(base);
  next.setHours(isNaN(hour) ? 0 : hour, isNaN(minute) ? 0 : minute, 0, 0);
  return next;
}
function startOfDay(date) {
  const next = new Date(date);
  next.setHours(0, 0, 0, 0);
  return next;
}
function DatePicker({
  value,
  onChange,
  placeholder,
  size = "default",
  disabled = false,
  readOnly = false,
  footer = "apply-cancel",
  closeOnSelect,
  showTodayButton = true,
  showClearButton = true,
  withTime = false,
  minuteStep = 1,
  align = "start",
  minDate,
  maxDate,
  locale,
  displayFormat,
  className,
  popoverClassName,
  id,
  name,
  required,
  "aria-label": ariaLabel,
  "aria-describedby": ariaDescribedBy
}) {
  const resolvedCloseOnSelect = closeOnSelect ?? footer === "today-clear";
  const t = useT();
  const [open, setOpen] = React.useState(false);
  const [draft, setDraft] = React.useState(value ?? null);
  const isInteractive = !disabled && !readOnly;
  const useDraft = footer === "apply-cancel";
  React.useEffect(() => {
    if (open) setDraft(value ?? null);
  }, [open, value]);
  const resolvedFormat = withTime ? resolvePublicDateTimeFormat(locale, displayFormat) : resolvePublicDateFormat(locale, displayFormat);
  const placeholderText = placeholder ?? (withTime ? t("ui.dateTimePicker.placeholder", "Pick date and time") : t("ui.datePicker.placeholder", "Pick a date"));
  const formattedValue = React.useMemo(() => {
    if (!value) return null;
    return formatWithPublicDateFormat(value, resolvedFormat, locale);
  }, [value, resolvedFormat, locale]);
  const handleDaySelect = React.useCallback(
    (day) => {
      if (!day || !isInteractive) return;
      const reference = withTime ? useDraft ? draft : value : null;
      const base = withTime ? applyTimeToDate(day, reference ? extractTime(reference) : "00:00") : startOfDay(day);
      if (useDraft) {
        setDraft(base);
      } else {
        onChange(base);
        if (footer === "none" || resolvedCloseOnSelect) setOpen(false);
      }
    },
    [isInteractive, withTime, useDraft, draft, value, footer, resolvedCloseOnSelect, onChange]
  );
  const handleTimeChange = React.useCallback(
    (time) => {
      const target = useDraft ? draft : value;
      if (!target) return;
      const next = applyTimeToDate(target, time);
      if (useDraft) setDraft(next);
      else onChange(next);
    },
    [useDraft, draft, value, onChange]
  );
  const handleApply = React.useCallback(() => {
    onChange(draft);
    setOpen(false);
  }, [draft, onChange]);
  const handleCancel = React.useCallback(() => {
    setDraft(value ?? null);
    setOpen(false);
  }, [value]);
  const handleToday = React.useCallback(() => {
    const today = withTime ? /* @__PURE__ */ new Date() : startOfDay(/* @__PURE__ */ new Date());
    onChange(today);
    setOpen(false);
  }, [withTime, onChange]);
  const handleClear = React.useCallback(() => {
    onChange(null);
    setOpen(false);
  }, [onChange]);
  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";
  const selectedDate = useDraft ? draft : value;
  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-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", popoverClassName), children: [
      /* @__PURE__ */ jsx(
        Calendar,
        {
          mode: "single",
          selected: selectedDate ?? void 0,
          onSelect: handleDaySelect,
          locale,
          disabled: disabledMatcher,
          autoFocus: true
        }
      ),
      withTime && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 border-t px-3 py-2", children: [
        /* @__PURE__ */ jsxs("span", { className: "text-sm text-muted-foreground shrink-0", children: [
          t("ui.datePicker.timeLabel", "Time"),
          ":"
        ] }),
        /* @__PURE__ */ jsx(
          TimeInput,
          {
            value: selectedDate ? extractTime(selectedDate) : void 0,
            onChange: handleTimeChange,
            minuteStep,
            disabled: !isInteractive || !selectedDate
          }
        )
      ] }),
      footer === "apply-cancel" && /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-2 border-t px-3 py-2", children: [
        /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "sm", onClick: handleCancel, children: t("ui.datePicker.cancelButton", "Cancel") }),
        /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", onClick: handleApply, children: t("ui.datePicker.applyButton", "Apply") })
      ] }),
      footer === "today-clear" && (showTodayButton || showClearButton) && /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2 border-t px-3 py-2", children: [
        showTodayButton ? /* @__PURE__ */ jsx(LinkButton, { type: "button", variant: "primary", onClick: handleToday, children: t("ui.datePicker.todayButton", "Today") }) : null,
        showClearButton ? /* @__PURE__ */ jsx(LinkButton, { type: "button", variant: "gray", onClick: handleClear, className: "ml-auto", children: t("ui.datePicker.clearButton", "Clear") }) : null
      ] })
    ] })
  ] });
}
export {
  DatePicker
};
//# sourceMappingURL=date-picker.js.map
