"use client";
'use strict';

const jsxRuntime = require('react/jsx-runtime');
const React = require('react');
const multiSelect = require('../../../../../../../ui/src/components/multi-select.cjs');
const button = require('../../../../../../../ui/src/components/button.cjs');
const LucideIcons = require('lucide-react');
const dialog = require('../../../../../../../ui/src/components/dialog.cjs');
const input = require('../../../../../../../ui/src/components/input.cjs');
const label = require('../../../../../../../ui/src/components/label.cjs');
const textarea = require('../../../../../../../ui/src/components/textarea.cjs');
const cmsHooks = require('../../hooks/cms-hooks.cjs');

function RelationField({
  field,
  fieldConfigItem,
  label: label$1,
  isRequired,
  relation
}) {
  const [isCreateDialogOpen, setIsCreateDialogOpen] = React.useState(false);
  const [newItemName, setNewItemName] = React.useState("");
  const [newItemDescription, setNewItemDescription] = React.useState("");
  const [createError, setCreateError] = React.useState(null);
  const isSingleSelect = relation.type === "belongsTo";
  const { items: availableItems, isLoading } = cmsHooks.useContent(relation.targetType, {
    limit: 100
    // Load a good chunk for the dropdown
  });
  const createMutation = cmsHooks.useCreateContent(relation.targetType);
  const normalizedValue = React.useMemo(() => {
    if (!field.value) return [];
    if (isSingleSelect) {
      const singleValue = field.value;
      if (singleValue && singleValue.id) {
        return [{ id: singleValue.id }];
      }
      return [];
    }
    return field.value || [];
  }, [field.value, isSingleSelect]);
  const selectedOptions = normalizedValue.map((v) => {
    const item = availableItems.find((item2) => item2.id === v.id);
    if (item) {
      const displayValue = item.parsedData?.[relation.displayField] || item.slug;
      return {
        value: item.id,
        label: String(displayValue)
      };
    }
    return { value: v.id, label: `ID: ${v.id.slice(0, 8)}...` };
  }).filter(Boolean);
  const options = availableItems.map((item) => {
    const displayValue = item.parsedData?.[relation.displayField] || item.slug;
    return {
      value: item.id,
      label: String(displayValue)
    };
  });
  const handleChange = React.useCallback(
    (newOptions) => {
      if (isSingleSelect) {
        if (newOptions.length > 0) {
          field.onChange({ id: newOptions[0].value });
        } else {
          field.onChange(void 0);
        }
      } else {
        const newValue = newOptions.map((opt) => ({ id: opt.value }));
        field.onChange(newValue);
      }
    },
    [field, isSingleSelect]
  );
  const handleCreateItem = async () => {
    if (!newItemName.trim()) return;
    setCreateError(null);
    try {
      const result = await createMutation.mutateAsync({
        slug: newItemName.toLowerCase().replace(/\s+/g, "-"),
        data: {
          [relation.displayField]: newItemName,
          description: newItemDescription || void 0
        }
      });
      if (isSingleSelect) {
        field.onChange({ id: result.id });
      } else {
        const newValue = [...normalizedValue, { id: result.id }];
        field.onChange(newValue);
      }
      setNewItemName("");
      setNewItemDescription("");
      setIsCreateDialogOpen(false);
    } catch (error) {
      const message = error instanceof Error ? error.message : "Failed to create item. Please try again.";
      setCreateError(message);
    }
  };
  const handleRemove = React.useCallback(
    (idToRemove) => {
      if (isSingleSelect) {
        field.onChange(void 0);
      } else {
        const newValue = normalizedValue.filter((v) => v.id !== idToRemove);
        field.onChange(newValue);
      }
    },
    [normalizedValue, field, isSingleSelect]
  );
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
    /* @__PURE__ */ jsxRuntime.jsxs(label.Label, { children: [
      label$1,
      isRequired && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-destructive ml-1", children: "*" })
    ] }),
    /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-2", children: [
      /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex-1", children: /* @__PURE__ */ jsxRuntime.jsx(
        multiSelect,
        {
          value: selectedOptions,
          onChange: handleChange,
          options,
          placeholder: isLoading ? "Loading..." : `Select ${relation.targetType}${isSingleSelect ? "" : "(s)"}...`,
          disabled: isLoading,
          hidePlaceholderWhenSelected: true,
          emptyIndicator: /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "text-center text-sm text-muted-foreground py-4", children: [
            "No ",
            relation.targetType,
            " items found"
          ] }),
          maxSelected: isSingleSelect ? 1 : void 0,
          className: "min-h-10"
        }
      ) }),
      relation.creatable && /* @__PURE__ */ jsxRuntime.jsxs(
        dialog.Dialog,
        {
          open: isCreateDialogOpen,
          onOpenChange: setIsCreateDialogOpen,
          children: [
            /* @__PURE__ */ jsxRuntime.jsx(dialog.DialogTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntime.jsx(button.Button, { type: "button", variant: "outline", size: "icon", children: /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.Plus, { className: "h-4 w-4" }) }) }),
            /* @__PURE__ */ jsxRuntime.jsxs(dialog.DialogContent, { children: [
              /* @__PURE__ */ jsxRuntime.jsx(dialog.DialogHeader, { children: /* @__PURE__ */ jsxRuntime.jsxs(dialog.DialogTitle, { children: [
                "Create New ",
                relation.targetType
              ] }) }),
              /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4 py-4", children: [
                createError && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-destructive", children: createError }),
                /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
                  /* @__PURE__ */ jsxRuntime.jsx(label.Label, { htmlFor: "newItemName", children: relation.displayField.charAt(0).toUpperCase() + relation.displayField.slice(1) }),
                  /* @__PURE__ */ jsxRuntime.jsx(
                    input.Input,
                    {
                      id: "newItemName",
                      value: newItemName,
                      onChange: (e) => setNewItemName(e.target.value),
                      placeholder: `Enter ${relation.displayField}...`
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
                  /* @__PURE__ */ jsxRuntime.jsx(label.Label, { htmlFor: "newItemDescription", children: "Description (optional)" }),
                  /* @__PURE__ */ jsxRuntime.jsx(
                    textarea.Textarea,
                    {
                      id: "newItemDescription",
                      value: newItemDescription,
                      onChange: (e) => setNewItemDescription(e.target.value),
                      placeholder: "Enter description...",
                      rows: 3
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex justify-end gap-2", children: [
                  /* @__PURE__ */ jsxRuntime.jsx(
                    button.Button,
                    {
                      type: "button",
                      variant: "outline",
                      onClick: () => setIsCreateDialogOpen(false),
                      children: "Cancel"
                    }
                  ),
                  /* @__PURE__ */ jsxRuntime.jsx(
                    button.Button,
                    {
                      type: "button",
                      onClick: handleCreateItem,
                      disabled: !newItemName.trim() || createMutation.isPending,
                      children: createMutation.isPending ? "Creating..." : "Create"
                    }
                  )
                ] })
              ] })
            ] })
          ]
        }
      )
    ] }),
    selectedOptions.length > 0 && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex flex-wrap gap-1 mt-2", children: selectedOptions.map((opt) => /* @__PURE__ */ jsxRuntime.jsxs(
      "div",
      {
        className: "inline-flex items-center gap-1 px-2 py-1 text-xs rounded-md bg-secondary text-secondary-foreground",
        children: [
          /* @__PURE__ */ jsxRuntime.jsx("span", { children: opt.label }),
          /* @__PURE__ */ jsxRuntime.jsx(
            "button",
            {
              type: "button",
              onClick: () => handleRemove(opt.value),
              className: "hover:text-destructive",
              children: /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.X, { className: "h-3 w-3" })
            }
          )
        ]
      },
      opt.value
    )) }),
    fieldConfigItem?.description && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: fieldConfigItem.description })
  ] });
}

exports.RelationField = RelationField;
