"use client";
import { jsxs, jsx } from 'react/jsx-runtime';
import { useState, useMemo, useCallback } from 'react';
import MultipleSelector from '../../../../../../../ui/src/components/multi-select.mjs';
import { Button } from '../../../../../../../ui/src/components/button.mjs';
import { Plus, X } from 'lucide-react';
import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle } from '../../../../../../../ui/src/components/dialog.mjs';
import { Input } from '../../../../../../../ui/src/components/input.mjs';
import { Label } from '../../../../../../../ui/src/components/label.mjs';
import { Textarea } from '../../../../../../../ui/src/components/textarea.mjs';
import { useContent, useCreateContent } from '../../hooks/cms-hooks.mjs';

function RelationField({
  field,
  fieldConfigItem,
  label,
  isRequired,
  relation
}) {
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [newItemName, setNewItemName] = useState("");
  const [newItemDescription, setNewItemDescription] = useState("");
  const [createError, setCreateError] = useState(null);
  const isSingleSelect = relation.type === "belongsTo";
  const { items: availableItems, isLoading } = useContent(relation.targetType, {
    limit: 100
    // Load a good chunk for the dropdown
  });
  const createMutation = useCreateContent(relation.targetType);
  const normalizedValue = 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 = 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 = 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__ */ jsxs("div", { className: "space-y-2", children: [
    /* @__PURE__ */ jsxs(Label, { children: [
      label,
      isRequired && /* @__PURE__ */ jsx("span", { className: "text-destructive ml-1", children: "*" })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
      /* @__PURE__ */ jsx("div", { className: "flex-1", children: /* @__PURE__ */ jsx(
        MultipleSelector,
        {
          value: selectedOptions,
          onChange: handleChange,
          options,
          placeholder: isLoading ? "Loading..." : `Select ${relation.targetType}${isSingleSelect ? "" : "(s)"}...`,
          disabled: isLoading,
          hidePlaceholderWhenSelected: true,
          emptyIndicator: /* @__PURE__ */ 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__ */ jsxs(
        Dialog,
        {
          open: isCreateDialogOpen,
          onOpenChange: setIsCreateDialogOpen,
          children: [
            /* @__PURE__ */ jsx(DialogTrigger, { asChild: true, children: /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "icon", children: /* @__PURE__ */ jsx(Plus, { className: "h-4 w-4" }) }) }),
            /* @__PURE__ */ jsxs(DialogContent, { children: [
              /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsxs(DialogTitle, { children: [
                "Create New ",
                relation.targetType
              ] }) }),
              /* @__PURE__ */ jsxs("div", { className: "space-y-4 py-4", children: [
                createError && /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: createError }),
                /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                  /* @__PURE__ */ jsx(Label, { htmlFor: "newItemName", children: relation.displayField.charAt(0).toUpperCase() + relation.displayField.slice(1) }),
                  /* @__PURE__ */ jsx(
                    Input,
                    {
                      id: "newItemName",
                      value: newItemName,
                      onChange: (e) => setNewItemName(e.target.value),
                      placeholder: `Enter ${relation.displayField}...`
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                  /* @__PURE__ */ jsx(Label, { htmlFor: "newItemDescription", children: "Description (optional)" }),
                  /* @__PURE__ */ jsx(
                    Textarea,
                    {
                      id: "newItemDescription",
                      value: newItemDescription,
                      onChange: (e) => setNewItemDescription(e.target.value),
                      placeholder: "Enter description...",
                      rows: 3
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxs("div", { className: "flex justify-end gap-2", children: [
                  /* @__PURE__ */ jsx(
                    Button,
                    {
                      type: "button",
                      variant: "outline",
                      onClick: () => setIsCreateDialogOpen(false),
                      children: "Cancel"
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    Button,
                    {
                      type: "button",
                      onClick: handleCreateItem,
                      disabled: !newItemName.trim() || createMutation.isPending,
                      children: createMutation.isPending ? "Creating..." : "Create"
                    }
                  )
                ] })
              ] })
            ] })
          ]
        }
      )
    ] }),
    selectedOptions.length > 0 && /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1 mt-2", children: selectedOptions.map((opt) => /* @__PURE__ */ jsxs(
      "div",
      {
        className: "inline-flex items-center gap-1 px-2 py-1 text-xs rounded-md bg-secondary text-secondary-foreground",
        children: [
          /* @__PURE__ */ jsx("span", { children: opt.label }),
          /* @__PURE__ */ jsx(
            "button",
            {
              type: "button",
              onClick: () => handleRemove(opt.value),
              className: "hover:text-destructive",
              children: /* @__PURE__ */ jsx(X, { className: "h-3 w-3" })
            }
          )
        ]
      },
      opt.value
    )) }),
    fieldConfigItem?.description && /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: fieldConfigItem.description })
  ] });
}

export { RelationField };
