"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { format } from "date-fns/format";
import { parseISO } from "date-fns/parseISO";
import { Label } from "@open-mercato/ui/primitives/label";
import { Input } from "@open-mercato/ui/primitives/input";
import { Textarea } from "@open-mercato/ui/primitives/textarea";
import { CheckboxField } from "@open-mercato/ui/primitives/checkbox-field";
import { DatePicker } from "@open-mercato/ui/primitives/date-picker";
import { TagInput } from "@open-mercato/ui/primitives/tag-input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { Checkbox } from "@open-mercato/ui/primitives/checkbox";
const SELECT_CLEAR_SENTINEL = "__deal_custom_field_select_clear__";
function toStringArray(value) {
  if (!Array.isArray(value)) return [];
  return value.filter((item) => typeof item === "string");
}
function toDate(value) {
  if (value instanceof Date) return value;
  if (typeof value === "string" && value) {
    const parsed = parseISO(value);
    return Number.isNaN(parsed.getTime()) ? null : parsed;
  }
  return null;
}
function useResolvedOptions(field) {
  const builtin = field.type === "custom" ? null : field;
  const staticOptions = builtin?.options;
  const loadOptions = builtin?.loadOptions;
  const [loadedOptions, setLoadedOptions] = React.useState([]);
  React.useEffect(() => {
    if (staticOptions && staticOptions.length > 0) return;
    if (typeof loadOptions !== "function") return;
    let cancelled = false;
    loadOptions().then((options) => {
      if (!cancelled) setLoadedOptions(options);
    }).catch(() => {
      if (!cancelled) setLoadedOptions([]);
    });
    return () => {
      cancelled = true;
    };
  }, [staticOptions, loadOptions]);
  if (staticOptions && staticOptions.length > 0) return staticOptions;
  return loadedOptions;
}
function FieldShell({
  label,
  required,
  description,
  error,
  children
}) {
  const fieldId = React.useId();
  const control = React.isValidElement(children) ? React.cloneElement(children, { id: fieldId }) : children;
  return /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
    label.trim().length > 0 ? /* @__PURE__ */ jsxs(Label, { htmlFor: fieldId, children: [
      label,
      required ? /* @__PURE__ */ jsx("span", { className: "text-destructive", children: " *" }) : null
    ] }) : null,
    control,
    description ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: description }) : null,
    error ? /* @__PURE__ */ jsx("p", { className: "text-xs text-status-error-text", children: error }) : null
  ] });
}
function DealCustomFieldControl({
  field,
  value,
  onChange,
  error,
  disabled = false
}) {
  const options = useResolvedOptions(field);
  const ariaInvalid = error ? true : void 0;
  if (field.type === "checkbox") {
    return /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
      /* @__PURE__ */ jsx(
        CheckboxField,
        {
          label: field.label,
          description: field.description,
          checked: value === true,
          onCheckedChange: (next) => onChange(next === true),
          disabled,
          "aria-invalid": ariaInvalid
        }
      ),
      error ? /* @__PURE__ */ jsx("p", { className: "text-xs text-status-error-text", children: error }) : null
    ] });
  }
  if (field.type === "custom") {
    return /* @__PURE__ */ jsx(
      FieldShell,
      {
        label: field.label,
        required: field.required,
        description: field.description,
        error,
        children: field.component({
          id: field.id,
          value,
          error,
          setValue: onChange,
          disabled,
          autoFocus: false
        })
      }
    );
  }
  let control;
  switch (field.type) {
    case "number":
      control = /* @__PURE__ */ jsx(
        Input,
        {
          type: "number",
          inputMode: "numeric",
          value: typeof value === "number" || typeof value === "string" ? String(value) : "",
          placeholder: field.placeholder,
          disabled,
          "aria-invalid": ariaInvalid,
          onChange: (event) => {
            const raw = event.target.value;
            if (raw === "") {
              onChange(void 0);
              return;
            }
            const parsed = Number(raw);
            onChange(Number.isNaN(parsed) ? raw : parsed);
          }
        }
      );
      break;
    case "date":
    case "datepicker":
      control = /* @__PURE__ */ jsx(
        DatePicker,
        {
          value: toDate(value),
          onChange: (date) => onChange(date ? format(date, "yyyy-MM-dd") : void 0),
          disabled,
          placeholder: field.placeholder,
          "aria-invalid": ariaInvalid
        }
      );
      break;
    case "datetime":
    case "datetime-local":
      control = /* @__PURE__ */ jsx(
        DatePicker,
        {
          withTime: true,
          value: toDate(value),
          onChange: (date) => onChange(date ? date.toISOString() : void 0),
          disabled,
          placeholder: field.placeholder,
          "aria-invalid": ariaInvalid
        }
      );
      break;
    case "tags":
      control = /* @__PURE__ */ jsx(
        TagInput,
        {
          value: toStringArray(value),
          onChange: (next) => onChange(next),
          placeholder: field.placeholder,
          disabled,
          "aria-invalid": ariaInvalid
        }
      );
      break;
    case "richtext":
      control = /* @__PURE__ */ jsx(
        Textarea,
        {
          value: value == null ? "" : String(value),
          placeholder: field.placeholder,
          disabled,
          "aria-invalid": ariaInvalid,
          onChange: (event) => onChange(event.target.value)
        }
      );
      break;
    case "select": {
      if (field.multiple) {
        const selected = toStringArray(value);
        control = /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-3", children: options.map((option) => {
          const checked = selected.includes(option.value);
          return /* @__PURE__ */ jsxs("label", { className: "inline-flex cursor-pointer items-center gap-2", children: [
            /* @__PURE__ */ jsx(
              Checkbox,
              {
                checked,
                disabled,
                onCheckedChange: (state) => {
                  const next = new Set(selected);
                  if (state === true) next.add(option.value);
                  else next.delete(option.value);
                  onChange(Array.from(next));
                }
              }
            ),
            /* @__PURE__ */ jsx("span", { className: "text-sm", children: option.label })
          ] }, option.value);
        }) });
      } else {
        const selectedValue = Array.isArray(value) ? String(value[0] ?? "") : value == null ? "" : String(value);
        control = /* @__PURE__ */ jsxs(
          Select,
          {
            value: selectedValue,
            disabled,
            onValueChange: (next) => {
              if (!next || next === SELECT_CLEAR_SENTINEL) {
                onChange(null);
                return;
              }
              onChange(next);
            },
            children: [
              /* @__PURE__ */ jsx(SelectTrigger, { "aria-invalid": ariaInvalid, children: /* @__PURE__ */ jsx(SelectValue, { placeholder: field.placeholder }) }),
              /* @__PURE__ */ jsxs(SelectContent, { children: [
                !field.required && selectedValue ? /* @__PURE__ */ jsx(SelectItem, { value: SELECT_CLEAR_SENTINEL, children: "\u2014" }) : null,
                options.filter((option) => option.value !== "").map((option) => /* @__PURE__ */ jsx(SelectItem, { value: option.value, children: option.label }, option.value))
              ] })
            ]
          }
        );
      }
      break;
    }
    case "text":
    default:
      control = /* @__PURE__ */ jsx(
        Input,
        {
          value: value == null ? "" : String(value),
          placeholder: field.placeholder,
          disabled,
          "aria-invalid": ariaInvalid,
          onChange: (event) => onChange(event.target.value)
        }
      );
      break;
  }
  return /* @__PURE__ */ jsx(
    FieldShell,
    {
      label: field.label,
      required: field.required,
      description: field.description,
      error,
      children: control
    }
  );
}
var dealCustomFieldControl_default = DealCustomFieldControl;
export {
  DealCustomFieldControl,
  dealCustomFieldControl_default as default
};
//# sourceMappingURL=dealCustomFieldControl.js.map
