import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { FormItem, FormLabel, FormControl, FormDescription } from '../../../components/form.mjs';
import { ChildrenSearchableSelect } from '../../../components/ui-builder/internal/form-fields/children-searchable-select.mjs';
import IconNameField from '../../../components/ui-builder/internal/form-fields/iconname-field.mjs';
import { Textarea } from '../../../components/textarea.mjs';
import { MinimalTiptapEditor } from '../../../components/minimal-tiptap/minimal-tiptap.mjs';
import { Tooltip, TooltipTrigger, TooltipContent } from '../../../components/tooltip.mjs';
import { useLayerStore } from '../store/layer-store.mjs';
import 'react';
import { isVariableReference } from '../../../components/ui-builder/types.mjs';
import { Link, LockKeyhole, Unlink } from 'lucide-react';
import { Button } from '../../../components/button.mjs';
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from '../../../components/dropdown-menu.mjs';
import 'clsx';
import 'tailwind-merge';
import { useEditorStore } from '../store/editor-store.mjs';
import { Card, CardContent } from '../../../components/card.mjs';
import { BreakpointClassNameControl } from '../../../components/ui-builder/internal/form-fields/classname-control/breakpoint-classname-control.mjs';
import { Label } from '../../../components/label.mjs';
import { Badge } from '../../../components/badge.mjs';

const classNameFieldOverrides = (layer) => {
  return {
    fieldType: ({
      label,
      isRequired,
      field,
      fieldConfigItem
    }) => /* @__PURE__ */ jsx(
      FormFieldWrapper,
      {
        label,
        isRequired,
        fieldConfigItem,
        children: /* @__PURE__ */ jsx(
          BreakpointClassNameControl,
          {
            value: field.value,
            onChange: field.onChange
          }
        )
      }
    )
  };
};
const childrenFieldOverrides = (layer) => {
  return {
    fieldType: ({
      label,
      isRequired,
      fieldConfigItem,
      field,
      fieldProps
    }) => /* @__PURE__ */ jsx(
      FormFieldWrapper,
      {
        label,
        isRequired,
        fieldConfigItem,
        children: /* @__PURE__ */ jsx(
          ChildrenSearchableSelect,
          {
            layer,
            onChange: field.onChange,
            ...fieldProps
          }
        )
      }
    )
  };
};
const iconNameFieldOverrides = (layer) => {
  return {
    fieldType: ({
      label,
      isRequired,
      field,
      fieldProps
    }) => /* @__PURE__ */ jsx(
      IconNameField,
      {
        label,
        isRequired,
        value: layer.props.iconName,
        onChange: field.onChange,
        ...fieldProps
      }
    )
  };
};
const childrenAsTextareaFieldOverrides = (layer, allowVariableBinding = false) => {
  return {
    renderParent: allowVariableBinding ? ({ children }) => /* @__PURE__ */ jsx(ChildrenVariableBindingWrapper, { children }) : void 0,
    fieldType: ({
      label,
      isRequired,
      fieldConfigItem,
      field,
      fieldProps
    }) => /* @__PURE__ */ jsx(
      FormFieldWrapper,
      {
        label,
        isRequired,
        fieldConfigItem,
        children: /* @__PURE__ */ jsx(
          Textarea,
          {
            value: typeof layer.children === "string" ? layer.children : "",
            onChange: field.onChange,
            ...fieldProps
          }
        )
      }
    )
  };
};
const childrenAsTipTapFieldOverrides = (layer, allowVariableBinding = false) => {
  return {
    renderParent: allowVariableBinding ? ({ children }) => /* @__PURE__ */ jsx(ChildrenVariableBindingWrapper, { children }) : void 0,
    fieldType: ({
      label,
      isRequired,
      fieldConfigItem,
      field,
      fieldProps
    }) => /* @__PURE__ */ jsx(
      FormFieldWrapper,
      {
        label,
        isRequired,
        fieldConfigItem,
        children: /* @__PURE__ */ jsx(
          MinimalTiptapEditor,
          {
            immediatelyRender: false,
            output: "markdown",
            editable: true,
            value: typeof layer.children === "string" ? layer.children : "",
            editorClassName: "focus:outline-none px-4 py-2 h-full",
            onChange: (content) => {
              if (typeof content === "string") {
                field.onChange(content);
              } else {
                console.warn("Tiptap content is not a string");
              }
            },
            ...fieldProps
          }
        )
      }
    )
  };
};
const memoizedCommonFieldOverrides = /* @__PURE__ */ new Map();
const commonFieldOverrides = (allowBinding = false) => {
  if (memoizedCommonFieldOverrides.has(allowBinding)) {
    return memoizedCommonFieldOverrides.get(allowBinding);
  }
  const overrides = {
    className: (layer) => classNameFieldOverrides(),
    children: (layer) => childrenFieldOverrides(layer)
  };
  memoizedCommonFieldOverrides.set(allowBinding, overrides);
  return overrides;
};
function FormFieldWrapper({
  label,
  isRequired,
  fieldConfigItem,
  children
}) {
  return /* @__PURE__ */ jsxs(FormItem, { className: "flex flex-col", children: [
    /* @__PURE__ */ jsxs(FormLabel, { children: [
      label,
      isRequired && /* @__PURE__ */ jsx("span", { className: "text-destructive", children: " *" })
    ] }),
    /* @__PURE__ */ jsx(FormControl, { children }),
    fieldConfigItem?.description && /* @__PURE__ */ jsx(FormDescription, { children: fieldConfigItem.description })
  ] });
}
function ChildrenVariableBindingWrapper({
  children
}) {
  const variables = useLayerStore((state) => state.variables);
  const selectedLayerId = useLayerStore((state) => state.selectedLayerId);
  const findLayerById = useLayerStore((state) => state.findLayerById);
  const isChildrenBindingImmutable = useLayerStore((state) => state.isChildrenBindingImmutable);
  const incrementRevision = useEditorStore((state) => state.incrementRevision);
  const unbindChildrenFromVariable = useLayerStore(
    (state) => state.unbindChildrenFromVariable
  );
  const bindChildrenToVariable = useLayerStore((state) => state.bindChildrenToVariable);
  const selectedLayer = findLayerById(selectedLayerId);
  if (!selectedLayer) {
    return /* @__PURE__ */ jsx(Fragment, { children });
  }
  const currentValue = selectedLayer.children;
  const isCurrentlyBound = isVariableReference(currentValue);
  const boundVariable = isCurrentlyBound ? variables.find((v) => v.id === currentValue.__variableRef) : null;
  const isImmutable = isChildrenBindingImmutable(selectedLayer.id);
  const handleBindToVariable = (variableId) => {
    bindChildrenToVariable(selectedLayer.id, variableId);
    incrementRevision();
  };
  const handleUnbind = () => {
    unbindChildrenFromVariable(selectedLayer.id);
    incrementRevision();
  };
  return /* @__PURE__ */ jsx("div", { className: "flex w-full gap-2 items-end", children: isCurrentlyBound && boundVariable ? (
    // Bound state - show variable info and unbind button
    /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 w-full", children: [
      /* @__PURE__ */ jsx(Label, { children: "Children" }),
      /* @__PURE__ */ jsxs("div", { className: "flex items-end gap-2 w-full", children: [
        /* @__PURE__ */ jsx(Card, { className: "w-full", children: /* @__PURE__ */ jsx(CardContent, { className: "py-1 px-4", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 w-full", children: [
          /* @__PURE__ */ jsx(Link, { className: "h-4 w-4 flex-shrink-0" }),
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col min-w-0 flex-1", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 w-full", children: [
              /* @__PURE__ */ jsx("span", { className: "font-medium", children: boundVariable.name }),
              /* @__PURE__ */ jsx("span", { className: "px-1.5 py-0.5 bg-muted rounded text-xs font-mono", children: boundVariable.type }),
              isImmutable && /* @__PURE__ */ jsx(Badge, { "data-testid": "immutable-children-badge", className: "rounded", children: /* @__PURE__ */ jsx(LockKeyhole, { strokeWidth: 3, className: "w-3 h-3" }) })
            ] }),
            /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground truncate", children: String(boundVariable.defaultValue) })
          ] })
        ] }) }) }),
        !isImmutable && /* @__PURE__ */ jsxs(Tooltip, { children: [
          /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
            Button,
            {
              variant: "outline",
              onClick: handleUnbind,
              className: "px-3 h-10",
              children: /* @__PURE__ */ jsx(Unlink, { className: "h-4 w-4" })
            }
          ) }),
          /* @__PURE__ */ jsx(TooltipContent, { children: "Unbind Variable" })
        ] })
      ] })
    ] })
  ) : (
    // Unbound state - show normal field with bind button
    /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx("div", { className: "flex-1", children }),
      /* @__PURE__ */ jsx("div", { className: "flex justify-end", children: /* @__PURE__ */ jsxs(DropdownMenu, { children: [
        /* @__PURE__ */ jsxs(Tooltip, { children: [
          /* @__PURE__ */ jsx(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", className: "px-3 h-10", children: /* @__PURE__ */ jsx(Link, { className: "h-4 w-4 my-1" }) }) }) }),
          /* @__PURE__ */ jsx(TooltipContent, { children: "Bind Children to Variable" })
        ] }),
        /* @__PURE__ */ jsxs(DropdownMenuContent, { align: "end", className: "w-56", children: [
          /* @__PURE__ */ jsx("div", { className: "px-2 py-1.5 text-xs font-medium text-muted-foreground border-b", children: "Bind Children to Variable" }),
          variables.filter((v) => v.type === "string").length > 0 ? variables.filter((v) => v.type === "string").map((variable) => /* @__PURE__ */ jsx(
            DropdownMenuItem,
            {
              onClick: () => handleBindToVariable(variable.id),
              className: "flex flex-col items-start p-3",
              children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 w-full", children: [
                /* @__PURE__ */ jsx(Link, { className: "h-4 w-4 flex-shrink-0" }),
                /* @__PURE__ */ jsxs("div", { className: "flex flex-col min-w-0 flex-1", children: [
                  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 ", children: [
                    /* @__PURE__ */ jsx("span", { className: "font-medium", children: variable.name }),
                    /* @__PURE__ */ jsx("span", { className: "px-1.5 py-0.5 bg-muted rounded text-xs font-mono", children: variable.type })
                  ] }),
                  /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground truncate", children: String(variable.defaultValue) })
                ] })
              ] })
            },
            variable.id
          )) : /* @__PURE__ */ jsx("div", { className: "px-3 py-2 text-xs text-muted-foreground", children: "No string variables defined" })
        ] })
      ] }) })
    ] })
  ) });
}

export { ChildrenVariableBindingWrapper, FormFieldWrapper, childrenAsTextareaFieldOverrides, childrenAsTipTapFieldOverrides, childrenFieldOverrides, classNameFieldOverrides, commonFieldOverrides, iconNameFieldOverrides };
