"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useState, useMemo, useRef } from "react";
import { useTranslations } from "next-intl";
import { useQuery } from "@tanstack/react-query";
import { Input } from "../../ui/input.js";
import { Textarea } from "../../ui/textarea.js";
import { Label } from "../../ui/label.js";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "../../ui/select.js";
import { ImageUpload } from "../../ui/image-upload.js";
import { RichTextEditor } from "../../ui/rich-text-editor.js";
import { MediaLibrary } from "../../media/MediaLibrary.js";
import { ChevronDown, ChevronRight, CalendarIcon, ImageIcon, X, Loader2, Check } from "lucide-react";
import { cn } from "../../../lib/utils/index.js";
import { sel } from "../../../lib/test/index.js";
import { Switch } from "../../ui/switch.js";
import { RadioGroup, RadioGroupItem } from "../../ui/radio-group.js";
import { Calendar } from "../../ui/calendar.js";
import { Popover, PopoverContent, PopoverTrigger } from "../../ui/popover.js";
import { Button } from "../../ui/button.js";
import { format } from "date-fns";
import { ArrayField } from "./array-field.js";
import { fetchWithTeam } from "../../../lib/api/entities.js";
import { resolveMediaUrl } from "../../../types/blocks.js";
function evaluateCondition(condition, values) {
  if (!condition) return true;
  const fieldValue = values[condition.field];
  switch (condition.operator) {
    case "equals":
      return fieldValue === condition.value;
    case "notEquals":
      return fieldValue !== condition.value;
    case "contains":
      return typeof fieldValue === "string" && fieldValue.includes(String(condition.value));
    case "greaterThan":
      return Number(fieldValue) > Number(condition.value);
    case "lessThan":
      return Number(fieldValue) < Number(condition.value);
    default:
      return true;
  }
}
function organizeFields(fields) {
  const ungrouped = [];
  const groupMap = /* @__PURE__ */ new Map();
  for (const field of fields) {
    if (field.group) {
      if (!groupMap.has(field.group)) {
        groupMap.set(field.group, {
          id: field.group,
          label: field.groupLabel || field.group,
          fields: []
        });
      }
      groupMap.get(field.group).fields.push(field);
    } else {
      ungrouped.push(field);
    }
  }
  return {
    ungrouped,
    groups: Array.from(groupMap.values())
  };
}
function MediaLibraryField({
  value,
  onChange,
  fieldName
}) {
  const [isOpen, setIsOpen] = useState(false);
  const t = useTranslations("admin.blockEditor.form");
  const displayUrl = resolveMediaUrl(value || void 0) || "";
  const handleSelect = (media) => {
    if (Array.isArray(media)) return;
    onChange({ mediaId: media.id, url: media.url });
    setIsOpen(false);
  };
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    displayUrl ? /* @__PURE__ */ jsxs(
      "div",
      {
        className: "relative group rounded-md overflow-hidden",
        "data-cy": sel("blockEditor.blockPropertiesPanel.form.mediaField.preview", { name: fieldName }),
        children: [
          /* @__PURE__ */ jsx("img", { src: displayUrl, alt: "", className: "w-full h-40 object-cover" }),
          /* @__PURE__ */ jsxs("div", { className: "absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2", children: [
            /* @__PURE__ */ jsx(
              Button,
              {
                type: "button",
                variant: "secondary",
                size: "sm",
                onClick: () => setIsOpen(true),
                "data-cy": sel("blockEditor.blockPropertiesPanel.form.mediaField.changeBtn", { name: fieldName }),
                children: t("changeImage")
              }
            ),
            /* @__PURE__ */ jsx(
              Button,
              {
                type: "button",
                variant: "destructive",
                size: "sm",
                onClick: () => onChange(""),
                "data-cy": sel("blockEditor.blockPropertiesPanel.form.mediaField.removeBtn", { name: fieldName }),
                children: /* @__PURE__ */ jsx(X, { className: "h-4 w-4" })
              }
            )
          ] })
        ]
      }
    ) : /* @__PURE__ */ jsxs(
      "div",
      {
        onClick: () => setIsOpen(true),
        className: "border-2 border-dashed rounded-md p-8 text-center cursor-pointer hover:border-primary/50 transition-colors",
        "data-cy": sel("blockEditor.blockPropertiesPanel.form.mediaField.empty", { name: fieldName }),
        children: [
          /* @__PURE__ */ jsx(ImageIcon, { className: "h-8 w-8 mx-auto mb-2 text-muted-foreground" }),
          /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("browseMedia") })
        ]
      }
    ),
    /* @__PURE__ */ jsx(
      MediaLibrary,
      {
        isOpen,
        onClose: () => setIsOpen(false),
        onSelect: handleSelect,
        mode: "single",
        allowedTypes: ["image"]
      }
    )
  ] });
}
function RelationshipField({
  field,
  value,
  onChange
}) {
  const t = useTranslations("admin.blockEditor.form");
  const displayField = field.displayField || "name";
  const valueField = field.valueField || "id";
  const isMulti = field.relationshipType === "manyToMany";
  const { data, isLoading, isError } = useQuery({
    queryKey: ["relationship-field", field.targetEntity],
    queryFn: async () => {
      const url = `/api/v1/${field.targetEntity}?limit=100`;
      const response = await fetchWithTeam(url);
      if (!response.ok) return [];
      const json = await response.json();
      return json.items || json.data || [];
    },
    enabled: !!field.targetEntity,
    staleTime: 1e3 * 60 * 5
  });
  if (isLoading) {
    return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm text-muted-foreground h-9", children: [
      /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin" }),
      /* @__PURE__ */ jsx("span", { children: t("loadingEntity", { entity: field.targetEntity }) })
    ] });
  }
  if (isError || !field.targetEntity) {
    return /* @__PURE__ */ jsx("div", { className: "text-sm text-destructive h-9 flex items-center", children: t("failedToLoad", { entity: field.targetEntity }) });
  }
  const items = data || [];
  if (isMulti) {
    const selectedIds = Array.isArray(value) ? value : [];
    const toggleItem = (itemId) => {
      const next = selectedIds.includes(itemId) ? selectedIds.filter((id) => id !== itemId) : [...selectedIds, itemId];
      onChange(next);
    };
    return /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
      selectedIds.length > 0 && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("selectedCount", { count: selectedIds.length }) }),
      /* @__PURE__ */ jsxs(
        "div",
        {
          className: "border rounded-md max-h-48 overflow-y-auto divide-y",
          "data-cy": sel("blockEditor.blockPropertiesPanel.form.field", { name: field.name }),
          children: [
            items.length === 0 && /* @__PURE__ */ jsx("div", { className: "px-3 py-4 text-sm text-muted-foreground text-center", children: t("noEntityFound", { entity: field.targetEntity }) }),
            items.map((item) => {
              const itemValue = String(item[valueField] ?? "");
              const itemLabel = String(
                item[displayField] ?? item["title"] ?? item["name"] ?? itemValue
              );
              const isChecked = selectedIds.includes(itemValue);
              return /* @__PURE__ */ jsxs(
                "button",
                {
                  type: "button",
                  className: "flex items-center gap-2 w-full px-3 py-2 hover:bg-muted/50 text-left",
                  onClick: () => toggleItem(itemValue),
                  children: [
                    /* @__PURE__ */ jsx(
                      "div",
                      {
                        className: cn(
                          "w-4 h-4 border rounded flex-shrink-0 flex items-center justify-center",
                          isChecked ? "bg-primary border-primary" : "border-input"
                        ),
                        children: isChecked && /* @__PURE__ */ jsx(Check, { className: "h-3 w-3 text-primary-foreground" })
                      }
                    ),
                    /* @__PURE__ */ jsx("span", { className: "text-sm truncate", children: itemLabel })
                  ]
                },
                itemValue
              );
            })
          ]
        }
      )
    ] });
  }
  return /* @__PURE__ */ jsxs(
    Select,
    {
      value: String(value || ""),
      onValueChange: (v) => onChange(v),
      children: [
        /* @__PURE__ */ jsx(
          SelectTrigger,
          {
            id: field.name,
            "data-cy": sel("blockEditor.blockPropertiesPanel.form.field", { name: field.name }),
            children: /* @__PURE__ */ jsx(SelectValue, { placeholder: field.placeholder || t("selectEntity", { entity: field.targetEntity }) })
          }
        ),
        /* @__PURE__ */ jsxs(SelectContent, { children: [
          items.map((item) => {
            const itemValue = String(item[valueField] ?? "");
            const itemLabel = String(
              item[displayField] ?? item["title"] ?? item["name"] ?? itemValue
            );
            return /* @__PURE__ */ jsx(SelectItem, { value: itemValue, children: itemLabel }, itemValue);
          }),
          items.length === 0 && /* @__PURE__ */ jsx("div", { className: "px-2 py-4 text-sm text-muted-foreground text-center", children: t("noEntityFound", { entity: field.targetEntity }) })
        ] })
      ]
    }
  );
}
function DynamicForm({ fieldDefinitions, values, onChange }) {
  const t = useTranslations("admin.blockEditor.form");
  const [formValues, setFormValues] = useState(values);
  const [collapsedGroups, setCollapsedGroups] = useState(/* @__PURE__ */ new Set());
  const isSyncingFromParent = useRef(false);
  const debounceTimer = useRef(null);
  const { ungrouped, groups } = useMemo(
    () => organizeFields(fieldDefinitions),
    [fieldDefinitions]
  );
  useEffect(() => {
    if (debounceTimer.current) {
      clearTimeout(debounceTimer.current);
      debounceTimer.current = null;
    }
    isSyncingFromParent.current = true;
    setFormValues(values);
    requestAnimationFrame(() => {
      isSyncingFromParent.current = false;
    });
  }, [values]);
  useEffect(() => {
    if (isSyncingFromParent.current) {
      return;
    }
    debounceTimer.current = setTimeout(() => {
      onChange(formValues);
    }, 500);
    return () => {
      if (debounceTimer.current) {
        clearTimeout(debounceTimer.current);
      }
    };
  }, [formValues, onChange]);
  const handleFieldChange = useCallback((fieldName, value) => {
    setFormValues((prev) => ({
      ...prev,
      [fieldName]: value
    }));
  }, []);
  const toggleGroup = (groupId) => {
    setCollapsedGroups((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(groupId)) {
        newSet.delete(groupId);
      } else {
        newSet.add(groupId);
      }
      return newSet;
    });
  };
  const renderField = (field, compact = false) => {
    var _a, _b;
    const value = formValues[field.name] ?? field.default ?? "";
    switch (field.type) {
      case "text":
        return /* @__PURE__ */ jsx(
          Input,
          {
            type: "text",
            value: String(value),
            onChange: (e) => handleFieldChange(field.name, e.target.value),
            placeholder: field.placeholder,
            required: field.required,
            "data-cy": sel("blockEditor.blockPropertiesPanel.form.field", { name: field.name })
          }
        );
      case "textarea":
        return /* @__PURE__ */ jsx(
          Textarea,
          {
            value: String(value),
            onChange: (e) => handleFieldChange(field.name, e.target.value),
            placeholder: field.placeholder,
            required: field.required,
            rows: field.rows || 4,
            "data-cy": sel("blockEditor.blockPropertiesPanel.form.field", { name: field.name })
          }
        );
      case "rich-text":
        return /* @__PURE__ */ jsx(
          RichTextEditor,
          {
            value: String(value),
            onChange: (newValue) => handleFieldChange(field.name, newValue),
            placeholder: field.placeholder,
            "data-cy": sel("blockEditor.blockPropertiesPanel.form.field", { name: field.name })
          }
        );
      case "url":
        return /* @__PURE__ */ jsx(
          Input,
          {
            type: "url",
            value: String(value),
            onChange: (e) => handleFieldChange(field.name, e.target.value),
            placeholder: field.placeholder || "https://example.com",
            required: field.required,
            "data-cy": sel("blockEditor.blockPropertiesPanel.form.field", { name: field.name })
          }
        );
      case "number":
        return /* @__PURE__ */ jsx(
          Input,
          {
            type: "number",
            value: Number(value),
            onChange: (e) => handleFieldChange(field.name, Number(e.target.value)),
            placeholder: field.placeholder,
            required: field.required,
            min: field.min,
            max: field.max,
            step: field.step,
            "data-cy": sel("blockEditor.blockPropertiesPanel.form.field", { name: field.name })
          }
        );
      case "select":
        return /* @__PURE__ */ jsxs(
          Select,
          {
            value: String(value),
            onValueChange: (newValue) => handleFieldChange(field.name, newValue),
            children: [
              /* @__PURE__ */ jsx(SelectTrigger, { "data-cy": sel("blockEditor.blockPropertiesPanel.form.field", { name: field.name }), children: /* @__PURE__ */ jsx(SelectValue, { placeholder: field.placeholder || t("selectPlaceholder") }) }),
              /* @__PURE__ */ jsx(SelectContent, { children: (_a = field.options) == null ? void 0 : _a.map((option) => /* @__PURE__ */ jsx(SelectItem, { value: String(option.value), children: option.label }, String(option.value))) })
            ]
          }
        );
      case "image":
        return /* @__PURE__ */ jsx(
          ImageUpload,
          {
            value: Array.isArray(value) ? value : [],
            onChange: (newValue) => handleFieldChange(field.name, newValue),
            maxImages: 1,
            "data-cy": sel("blockEditor.blockPropertiesPanel.form.field", { name: field.name })
          }
        );
      case "media-library":
        return /* @__PURE__ */ jsx(
          MediaLibraryField,
          {
            value: value || "",
            onChange: (ref) => handleFieldChange(field.name, ref || void 0),
            fieldName: field.name
          }
        );
      case "array":
        return /* @__PURE__ */ jsx(
          ArrayField,
          {
            field,
            value: Array.isArray(value) ? value : [],
            onChange: (newValue) => handleFieldChange(field.name, newValue)
          }
        );
      case "checkbox":
        return /* @__PURE__ */ jsxs("div", { className: "flex items-center space-x-2", children: [
          /* @__PURE__ */ jsx(
            Switch,
            {
              id: field.name,
              checked: Boolean(value),
              onCheckedChange: (checked) => handleFieldChange(field.name, checked),
              "data-cy": sel("blockEditor.blockPropertiesPanel.form.field", { name: field.name })
            }
          ),
          /* @__PURE__ */ jsx(Label, { htmlFor: field.name, className: "text-sm font-normal cursor-pointer", children: field.checkboxLabel || field.label })
        ] });
      case "radio":
        return /* @__PURE__ */ jsx(
          RadioGroup,
          {
            value: String(value || ""),
            onValueChange: (newValue) => handleFieldChange(field.name, newValue),
            "data-cy": sel("blockEditor.blockPropertiesPanel.form.field", { name: field.name }),
            children: (_b = field.options) == null ? void 0 : _b.map((option) => /* @__PURE__ */ jsxs("div", { className: "flex items-center space-x-2", children: [
              /* @__PURE__ */ jsx(
                RadioGroupItem,
                {
                  value: String(option.value),
                  id: `${field.name}-${option.value}`
                }
              ),
              /* @__PURE__ */ jsx(
                Label,
                {
                  htmlFor: `${field.name}-${option.value}`,
                  className: "font-normal cursor-pointer",
                  children: option.label
                }
              )
            ] }, String(option.value)))
          }
        );
      case "color":
        return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsx(
            "div",
            {
              className: "w-10 h-10 rounded border cursor-pointer relative overflow-hidden",
              style: { backgroundColor: String(value || "#000000") },
              children: /* @__PURE__ */ jsx(
                Input,
                {
                  type: "color",
                  value: String(value || "#000000"),
                  onChange: (e) => handleFieldChange(field.name, e.target.value),
                  className: "opacity-0 w-full h-full cursor-pointer absolute inset-0",
                  "data-cy": sel("blockEditor.blockPropertiesPanel.form.field", { name: field.name })
                }
              )
            }
          ),
          /* @__PURE__ */ jsx(
            Input,
            {
              type: "text",
              value: String(value || "#000000"),
              onChange: (e) => handleFieldChange(field.name, e.target.value),
              placeholder: "#000000",
              className: "flex-1 font-mono text-sm"
            }
          )
        ] });
      case "date":
        return /* @__PURE__ */ jsxs(Popover, { children: [
          /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
            Button,
            {
              variant: "outline",
              className: cn(
                "w-full justify-start text-left font-normal",
                !value && "text-muted-foreground"
              ),
              "data-cy": sel("blockEditor.blockPropertiesPanel.form.field", { name: field.name }),
              children: [
                /* @__PURE__ */ jsx(CalendarIcon, { className: "mr-2 h-4 w-4" }),
                value ? format(new Date(String(value)), "PPP") : t("pickDate")
              ]
            }
          ) }),
          /* @__PURE__ */ jsx(PopoverContent, { className: "w-auto p-0", align: "start", children: /* @__PURE__ */ jsx(
            Calendar,
            {
              mode: "single",
              selected: value ? new Date(String(value)) : void 0,
              onSelect: (date) => handleFieldChange(field.name, date == null ? void 0 : date.toISOString().split("T")[0]),
              initialFocus: true
            }
          ) })
        ] });
      case "time":
        return /* @__PURE__ */ jsx(
          Input,
          {
            type: "time",
            value: String(value || ""),
            onChange: (e) => handleFieldChange(field.name, e.target.value),
            "data-cy": sel("blockEditor.blockPropertiesPanel.form.field", { name: field.name })
          }
        );
      case "datetime":
        return /* @__PURE__ */ jsx(
          Input,
          {
            type: "datetime-local",
            value: value ? String(value).slice(0, 16) : "",
            onChange: (e) => {
              const dateValue = e.target.value ? new Date(e.target.value).toISOString() : "";
              handleFieldChange(field.name, dateValue);
            },
            "data-cy": sel("blockEditor.blockPropertiesPanel.form.field", { name: field.name })
          }
        );
      case "relationship": {
        const isMulti = field.relationshipType === "manyToMany";
        const relationValue = isMulti ? Array.isArray(value) ? value : [] : String(value || "");
        return /* @__PURE__ */ jsx(
          RelationshipField,
          {
            field,
            value: relationValue,
            onChange: (newValue) => handleFieldChange(field.name, newValue)
          }
        );
      }
      default:
        return /* @__PURE__ */ jsx(
          Input,
          {
            type: "text",
            value: String(value),
            onChange: (e) => handleFieldChange(field.name, e.target.value),
            placeholder: field.placeholder,
            "data-cy": sel("blockEditor.blockPropertiesPanel.form.field", { name: field.name })
          }
        );
    }
  };
  const renderFieldWithLabel = (field, compact = false) => /* @__PURE__ */ jsxs("div", { className: cn("space-y-1.5", compact && "space-y-1"), children: [
    /* @__PURE__ */ jsxs(Label, { htmlFor: field.name, className: cn(compact && "text-xs"), children: [
      field.label,
      field.required && /* @__PURE__ */ jsx("span", { className: "text-destructive ml-1", children: "*" })
    ] }),
    renderField(field, compact),
    field.helpText && !compact && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: field.helpText })
  ] }, field.name);
  const renderArrayFieldAsGroup = (field) => {
    const isCollapsed = collapsedGroups.has(field.name);
    const value = formValues[field.name];
    const items = Array.isArray(value) ? value : [];
    const hasValue = items.length > 0;
    return /* @__PURE__ */ jsxs(
      "div",
      {
        className: "border rounded-lg overflow-hidden",
        "data-cy": sel("blockEditor.blockPropertiesPanel.form.arrayField.container", { name: field.name }),
        children: [
          /* @__PURE__ */ jsxs(
            "button",
            {
              type: "button",
              className: cn(
                "flex items-center justify-between w-full px-3 py-2 text-sm font-medium",
                "bg-muted/50 hover:bg-muted/70 transition-colors text-left",
                hasValue && "bg-primary/5"
              ),
              onClick: () => toggleGroup(field.name),
              children: [
                /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-2", children: [
                  isCollapsed ? /* @__PURE__ */ jsx(ChevronRight, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4" }),
                  field.label,
                  field.required && /* @__PURE__ */ jsx("span", { className: "text-destructive", children: "*" })
                ] }),
                hasValue && /* @__PURE__ */ jsx("span", { className: "text-xs text-primary font-normal", children: t("arrayItemsCount", { count: items.length }) })
              ]
            }
          ),
          !isCollapsed && /* @__PURE__ */ jsxs("div", { className: "p-3 bg-card", children: [
            renderField(field),
            field.helpText && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mt-2", children: field.helpText })
          ] })
        ]
      },
      field.name
    );
  };
  const renderGroup = (group) => {
    const isCollapsed = collapsedGroups.has(group.id);
    const hasValue = group.fields.some((field) => {
      const value = formValues[field.name];
      return value !== void 0 && value !== "" && value !== null;
    });
    return /* @__PURE__ */ jsxs(
      "div",
      {
        className: "border rounded-lg overflow-hidden",
        "data-cy": sel("blockEditor.blockPropertiesPanel.form.fieldGroup", { id: group.id }),
        children: [
          /* @__PURE__ */ jsxs(
            "button",
            {
              type: "button",
              className: cn(
                "flex items-center justify-between w-full px-3 py-2 text-sm font-medium",
                "bg-muted/50 hover:bg-muted/70 transition-colors text-left",
                hasValue && "bg-primary/5"
              ),
              onClick: () => toggleGroup(group.id),
              children: [
                /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-2", children: [
                  isCollapsed ? /* @__PURE__ */ jsx(ChevronRight, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4" }),
                  group.label
                ] }),
                hasValue && /* @__PURE__ */ jsx("span", { className: "text-xs text-primary font-normal", children: t("configured") })
              ]
            }
          ),
          !isCollapsed && /* @__PURE__ */ jsx("div", { className: "p-3 space-y-3 bg-card", children: group.fields.map((field) => renderFieldWithLabel(field, true)) })
        ]
      },
      group.id
    );
  };
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", "data-cy": sel("blockEditor.blockPropertiesPanel.form.container"), children: [
    ungrouped.filter((field) => evaluateCondition(field.condition, formValues)).map(
      (field) => field.type === "array" ? renderArrayFieldAsGroup(field) : renderFieldWithLabel(field)
    ),
    groups.map((group) => renderGroup(group))
  ] });
}
export {
  DynamicForm
};
