"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useState, useCallback, useMemo } from "react";
import { useTranslations } from "next-intl";
import { useQuery } from "@tanstack/react-query";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger
} from "../../ui/collapsible.js";
import { ScrollArea } from "../../ui/scroll-area.js";
import { Input } from "../../ui/input.js";
import { Textarea } from "../../ui/textarea.js";
import { Label } from "../../ui/label.js";
import { Badge } from "../../ui/badge.js";
import { Button } from "../../ui/button.js";
import { Checkbox } from "../../ui/checkbox.js";
import {
  ChevronDown,
  FileText,
  Image,
  Tag,
  Search,
  Settings2,
  Plus,
  Trash2,
  Loader2
} from "lucide-react";
import { cn } from "../../../lib/utils/index.js";
import { sel } from "../../../lib/test/index.js";
import { SimpleRelationSelect } from "../../ui/simple-relation-select.js";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "../../ui/select.js";
function ConfigPanel({
  entityConfig,
  entityFields,
  onEntityFieldChange,
  pageSettings,
  onPageSettingsChange
}) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
  const t = useTranslations("admin.builder");
  const tSettings = useTranslations("admin.pages.settings");
  const [entityFieldsOpen, setEntityFieldsOpen] = useState(true);
  const [seoOpen, setSeoOpen] = useState(true);
  const [customFieldsOpen, setCustomFieldsOpen] = useState(true);
  const sidebarFields = ((_a = entityConfig.builder) == null ? void 0 : _a.sidebarFields) || [];
  const taxonomyTypes = ((_b = entityConfig.taxonomies) == null ? void 0 : _b.types) || [];
  const taxonomiesEnabled = ((_c = entityConfig.taxonomies) == null ? void 0 : _c.enabled) && taxonomyTypes.length > 0;
  const firstTaxonomy = taxonomyTypes[0];
  const taxonomyApiPath = (firstTaxonomy == null ? void 0 : firstTaxonomy.type) ? firstTaxonomy.type.replace("_", "-") + "s" : void 0;
  const { data: taxonomyData, isLoading: taxonomyLoading } = useQuery({
    queryKey: ["taxonomies", taxonomyApiPath],
    queryFn: async () => {
      if (!taxonomyApiPath) return { data: [] };
      const response = await fetch(`/api/v1/${taxonomyApiPath}`);
      if (!response.ok) return { data: [] };
      return response.json();
    },
    enabled: taxonomiesEnabled && !!taxonomyApiPath
  });
  const taxonomyItems = (taxonomyData == null ? void 0 : taxonomyData.data) || [];
  const currentCategories = entityFields.categories || [];
  const showEntityFieldsSection = useMemo(() => {
    return sidebarFields.length > 0 || taxonomiesEnabled;
  }, [sidebarFields.length, taxonomiesEnabled]);
  const showSeoSection = ((_d = entityConfig.builder) == null ? void 0 : _d.seo) !== false;
  const renderField = (fieldName) => {
    var _a2;
    const value = entityFields[fieldName];
    const sidebarFieldsConfig = (_a2 = entityConfig.builder) == null ? void 0 : _a2.sidebarFieldsConfig;
    const fieldConfig = sidebarFieldsConfig == null ? void 0 : sidebarFieldsConfig.find((f) => f.name === fieldName);
    if (fieldConfig == null ? void 0 : fieldConfig.conditionalOn) {
      const { field: depField, value: depValue } = fieldConfig.conditionalOn;
      const currentDepValue = entityFields[depField];
      const allowedValues = Array.isArray(depValue) ? depValue : [depValue];
      if (!currentDepValue || !allowedValues.includes(currentDepValue)) {
        return null;
      }
    }
    const fieldLabel = (fieldConfig == null ? void 0 : fieldConfig.label) || fieldName.charAt(0).toUpperCase() + fieldName.slice(1).replace(/([A-Z])/g, " $1");
    if ((fieldConfig == null ? void 0 : fieldConfig.type) === "relation" && fieldConfig.relation) {
      return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: fieldName, children: fieldLabel }),
        /* @__PURE__ */ jsx(
          SimpleRelationSelect,
          {
            id: fieldName,
            entityType: fieldConfig.relation.entity,
            titleField: fieldConfig.relation.titleField,
            value: value || void 0,
            onChange: (v) => onEntityFieldChange(fieldName, v ?? null),
            userFiltered: fieldConfig.relation.userFiltered,
            placeholder: "Select...",
            limit: fieldConfig.relation.limit,
            filter: fieldConfig.relation.filter
          }
        )
      ] }, fieldName);
    }
    if ((fieldConfig == null ? void 0 : fieldConfig.type) === "select" && fieldConfig.options) {
      return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: fieldName, children: fieldLabel }),
        /* @__PURE__ */ jsxs(Select, { value: value || "", onValueChange: (v) => onEntityFieldChange(fieldName, v), children: [
          /* @__PURE__ */ jsx(SelectTrigger, { id: fieldName, children: /* @__PURE__ */ jsx(SelectValue, { placeholder: "Select..." }) }),
          /* @__PURE__ */ jsx(SelectContent, { children: fieldConfig.options.map((opt) => /* @__PURE__ */ jsx(SelectItem, { value: opt.value, children: opt.label }, opt.value)) })
        ] })
      ] }, fieldName);
    }
    const isTextarea = fieldName.toLowerCase().includes("excerpt") || fieldName.toLowerCase().includes("description") || fieldName.toLowerCase().includes("summary");
    const isImage = fieldName.toLowerCase().includes("image") || fieldName.toLowerCase().includes("thumbnail") || fieldName.toLowerCase().includes("photo");
    if (isTextarea) {
      return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsxs(Label, { htmlFor: fieldName, className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsx(FileText, { className: "h-4 w-4 text-muted-foreground" }),
          fieldLabel
        ] }),
        /* @__PURE__ */ jsx(
          Textarea,
          {
            id: fieldName,
            value: value || "",
            onChange: (e) => onEntityFieldChange(fieldName, e.target.value),
            placeholder: t("placeholders.excerpt"),
            rows: 4,
            className: "resize-none",
            "data-cy": sel("blockEditor.configPanel.entityFieldsSection.field", { name: fieldName })
          }
        )
      ] }, fieldName);
    }
    if (isImage) {
      return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsxs(Label, { htmlFor: fieldName, className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsx(Image, { className: "h-4 w-4 text-muted-foreground" }),
          fieldLabel
        ] }),
        /* @__PURE__ */ jsx(
          Input,
          {
            id: fieldName,
            type: "url",
            value: value || "",
            onChange: (e) => onEntityFieldChange(fieldName, e.target.value),
            placeholder: t("placeholders.imageUrl"),
            "data-cy": sel("blockEditor.configPanel.entityFieldsSection.field", { name: fieldName })
          }
        ),
        value && /* @__PURE__ */ jsx("div", { className: "mt-2 rounded-md border overflow-hidden", children: /* @__PURE__ */ jsx(
          "img",
          {
            src: value,
            alt: fieldLabel,
            className: "w-full h-32 object-cover",
            onError: (e) => {
              e.target.style.display = "none";
            }
          }
        ) })
      ] }, fieldName);
    }
    return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsx(Label, { htmlFor: fieldName, children: fieldLabel }),
      /* @__PURE__ */ jsx(
        Input,
        {
          id: fieldName,
          value: value || "",
          onChange: (e) => onEntityFieldChange(fieldName, e.target.value),
          "data-cy": sel("blockEditor.configPanel.entityFieldsSection.field", { name: fieldName })
        }
      )
    ] }, fieldName);
  };
  const handleCategoryClick = useCallback((categoryId) => {
    const newCategories = currentCategories.includes(categoryId) ? currentCategories.filter((id) => id !== categoryId) : [...currentCategories, categoryId];
    onEntityFieldChange("categories", newCategories);
  }, [currentCategories, onEntityFieldChange]);
  const handleSeoChange = useCallback((field, value) => {
    onPageSettingsChange({
      seo: { ...pageSettings.seo || {}, [field]: value },
      customFields: pageSettings.customFields || []
    });
  }, [pageSettings, onPageSettingsChange]);
  const handleAddCustomField = useCallback(() => {
    onPageSettingsChange({
      seo: pageSettings.seo || {},
      customFields: [...pageSettings.customFields || [], { key: "", value: "" }]
    });
  }, [pageSettings, onPageSettingsChange]);
  const handleUpdateCustomField = useCallback((index, field, value) => {
    const newFields = (pageSettings.customFields || []).map(
      (f, i) => i === index ? { ...f, [field]: value } : f
    );
    onPageSettingsChange({
      seo: pageSettings.seo || {},
      customFields: newFields
    });
  }, [pageSettings, onPageSettingsChange]);
  const handleRemoveCustomField = useCallback((index) => {
    onPageSettingsChange({
      seo: pageSettings.seo || {},
      customFields: (pageSettings.customFields || []).filter((_, i) => i !== index)
    });
  }, [pageSettings, onPageSettingsChange]);
  return /* @__PURE__ */ jsx(
    "div",
    {
      "data-cy": sel("blockEditor.configPanel.container"),
      className: "h-full bg-background",
      children: /* @__PURE__ */ jsx(
        ScrollArea,
        {
          "data-cy": sel("blockEditor.configPanel.scroll"),
          className: "h-full",
          children: /* @__PURE__ */ jsxs("div", { className: "max-w-4xl mx-auto p-6 space-y-4", children: [
            showEntityFieldsSection && /* @__PURE__ */ jsxs(
              Collapsible,
              {
                open: entityFieldsOpen,
                onOpenChange: setEntityFieldsOpen,
                "data-cy": sel("blockEditor.configPanel.entityFieldsSection.container"),
                className: "bg-card rounded-lg border",
                children: [
                  /* @__PURE__ */ jsxs(
                    CollapsibleTrigger,
                    {
                      "data-cy": sel("blockEditor.configPanel.entityFieldsSection.trigger"),
                      className: "flex items-center justify-between w-full p-4 hover:bg-accent/50 transition-colors cursor-pointer",
                      children: [
                        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                          /* @__PURE__ */ jsx(FileText, { className: "h-4 w-4 text-muted-foreground" }),
                          /* @__PURE__ */ jsx("h3", { className: "font-semibold", children: t("config.entityFields") })
                        ] }),
                        /* @__PURE__ */ jsx(ChevronDown, { className: cn(
                          "h-4 w-4 text-muted-foreground transition-transform",
                          entityFieldsOpen && "rotate-180"
                        ) })
                      ]
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    CollapsibleContent,
                    {
                      "data-cy": sel("blockEditor.configPanel.entityFieldsSection.content"),
                      children: /* @__PURE__ */ jsxs("div", { className: "space-y-6 px-4 pb-4 pt-2 border-t", children: [
                        sidebarFields.length > 0 && /* @__PURE__ */ jsx("div", { className: "space-y-4", children: sidebarFields.map((fieldName) => renderField(fieldName)) }),
                        taxonomiesEnabled && firstTaxonomy && /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
                          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                            /* @__PURE__ */ jsx(Tag, { className: "h-4 w-4 text-muted-foreground" }),
                            /* @__PURE__ */ jsx(Label, { children: firstTaxonomy.label || "Categories" })
                          ] }),
                          taxonomyLoading ? /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center py-4", children: /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin text-muted-foreground" }) }) : taxonomyItems.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("sidebar.noCategories") }) : /* @__PURE__ */ jsx("div", { className: "space-y-2", children: taxonomyItems.map((item) => /* @__PURE__ */ jsxs(
                            "div",
                            {
                              className: "flex items-center gap-2 rounded-md border p-2 hover:bg-accent transition-colors cursor-pointer",
                              onClick: () => handleCategoryClick(item.id),
                              children: [
                                /* @__PURE__ */ jsx(
                                  Checkbox,
                                  {
                                    checked: currentCategories.includes(item.id),
                                    onCheckedChange: () => handleCategoryClick(item.id)
                                  }
                                ),
                                /* @__PURE__ */ jsx("span", { className: "text-sm flex-1", children: item.name }),
                                item.color && /* @__PURE__ */ jsx(
                                  "div",
                                  {
                                    className: "h-3 w-3 rounded-full",
                                    style: { backgroundColor: item.color }
                                  }
                                )
                              ]
                            },
                            item.id
                          )) }),
                          currentCategories.length > 0 && /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1 pt-2", children: currentCategories.map((catId) => {
                            const cat = taxonomyItems.find((t2) => t2.id === catId);
                            return cat ? /* @__PURE__ */ jsxs(
                              Badge,
                              {
                                variant: "secondary",
                                className: "cursor-pointer",
                                onClick: () => handleCategoryClick(cat.id),
                                style: cat.color ? { backgroundColor: cat.color, color: "#fff" } : void 0,
                                children: [
                                  cat.name,
                                  " \xD7"
                                ]
                              },
                              cat.id
                            ) : null;
                          }) })
                        ] })
                      ] })
                    }
                  )
                ]
              }
            ),
            showSeoSection && /* @__PURE__ */ jsxs(
              Collapsible,
              {
                open: seoOpen,
                onOpenChange: setSeoOpen,
                "data-cy": sel("blockEditor.configPanel.seoSection.container"),
                className: "bg-card rounded-lg border",
                children: [
                  /* @__PURE__ */ jsxs(
                    CollapsibleTrigger,
                    {
                      "data-cy": sel("blockEditor.configPanel.seoSection.trigger"),
                      className: "flex items-center justify-between w-full p-4 hover:bg-accent/50 transition-colors cursor-pointer",
                      children: [
                        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                          /* @__PURE__ */ jsx(Search, { className: "h-4 w-4 text-muted-foreground" }),
                          /* @__PURE__ */ jsx("h3", { className: "font-semibold", children: t("config.seo") })
                        ] }),
                        /* @__PURE__ */ jsx(ChevronDown, { className: cn(
                          "h-4 w-4 text-muted-foreground transition-transform",
                          seoOpen && "rotate-180"
                        ) })
                      ]
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    CollapsibleContent,
                    {
                      "data-cy": sel("blockEditor.configPanel.seoSection.content"),
                      children: /* @__PURE__ */ jsxs("div", { className: "space-y-6 px-4 pb-4 pt-2 border-t", children: [
                        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                          /* @__PURE__ */ jsx(Label, { htmlFor: "meta-title", children: tSettings("seo.metaTitle") }),
                          /* @__PURE__ */ jsx(
                            Input,
                            {
                              id: "meta-title",
                              value: ((_e = pageSettings.seo) == null ? void 0 : _e.metaTitle) || "",
                              onChange: (e) => handleSeoChange("metaTitle", e.target.value),
                              placeholder: tSettings("seo.metaTitlePlaceholder"),
                              "data-cy": sel("blockEditor.configPanel.seoSection.metaTitle")
                            }
                          ),
                          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: tSettings("seo.metaTitleHint") })
                        ] }),
                        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                          /* @__PURE__ */ jsx(Label, { htmlFor: "meta-description", children: tSettings("seo.metaDescription") }),
                          /* @__PURE__ */ jsx(
                            Textarea,
                            {
                              id: "meta-description",
                              value: ((_f = pageSettings.seo) == null ? void 0 : _f.metaDescription) || "",
                              onChange: (e) => handleSeoChange("metaDescription", e.target.value),
                              placeholder: tSettings("seo.metaDescriptionPlaceholder"),
                              rows: 3,
                              "data-cy": sel("blockEditor.configPanel.seoSection.metaDescription")
                            }
                          ),
                          /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
                            ((_h = (_g = pageSettings.seo) == null ? void 0 : _g.metaDescription) == null ? void 0 : _h.length) || 0,
                            "/160 ",
                            tSettings("seo.characters")
                          ] })
                        ] }),
                        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                          /* @__PURE__ */ jsx(Label, { htmlFor: "meta-keywords", children: tSettings("seo.metaKeywords") }),
                          /* @__PURE__ */ jsx(
                            Input,
                            {
                              id: "meta-keywords",
                              value: ((_i = pageSettings.seo) == null ? void 0 : _i.metaKeywords) || "",
                              onChange: (e) => handleSeoChange("metaKeywords", e.target.value),
                              placeholder: tSettings("seo.metaKeywordsPlaceholder"),
                              "data-cy": sel("blockEditor.configPanel.seoSection.metaKeywords")
                            }
                          )
                        ] }),
                        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                          /* @__PURE__ */ jsx(Label, { htmlFor: "og-image", children: tSettings("seo.ogImage") }),
                          /* @__PURE__ */ jsx(
                            Input,
                            {
                              id: "og-image",
                              value: ((_j = pageSettings.seo) == null ? void 0 : _j.ogImage) || "",
                              onChange: (e) => handleSeoChange("ogImage", e.target.value),
                              placeholder: tSettings("seo.ogImagePlaceholder"),
                              "data-cy": sel("blockEditor.configPanel.seoSection.ogImage")
                            }
                          )
                        ] })
                      ] })
                    }
                  )
                ]
              }
            ),
            /* @__PURE__ */ jsxs(
              Collapsible,
              {
                open: customFieldsOpen,
                onOpenChange: setCustomFieldsOpen,
                "data-cy": sel("blockEditor.configPanel.customFieldsSection.container"),
                className: "bg-card rounded-lg border",
                children: [
                  /* @__PURE__ */ jsxs(
                    CollapsibleTrigger,
                    {
                      "data-cy": sel("blockEditor.configPanel.customFieldsSection.trigger"),
                      className: "flex items-center justify-between w-full p-4 hover:bg-accent/50 transition-colors cursor-pointer",
                      children: [
                        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                          /* @__PURE__ */ jsx(Settings2, { className: "h-4 w-4 text-muted-foreground" }),
                          /* @__PURE__ */ jsx("h3", { className: "font-semibold", children: tSettings("customFields.title") })
                        ] }),
                        /* @__PURE__ */ jsx(ChevronDown, { className: cn(
                          "h-4 w-4 text-muted-foreground transition-transform",
                          customFieldsOpen && "rotate-180"
                        ) })
                      ]
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    CollapsibleContent,
                    {
                      "data-cy": sel("blockEditor.configPanel.customFieldsSection.content"),
                      children: /* @__PURE__ */ jsxs("div", { className: "space-y-4 px-4 pb-4 pt-2 border-t", children: [
                        (pageSettings.customFields || []).length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground text-center py-4", children: tSettings("customFields.empty") }) : /* @__PURE__ */ jsx("div", { className: "space-y-3", children: (pageSettings.customFields || []).map((field, index) => /* @__PURE__ */ jsxs("div", { className: "flex gap-2 items-start", children: [
                          /* @__PURE__ */ jsx("div", { className: "flex-1", children: /* @__PURE__ */ jsx(
                            Input,
                            {
                              value: field.key,
                              onChange: (e) => handleUpdateCustomField(index, "key", e.target.value),
                              placeholder: tSettings("customFields.keyPlaceholder"),
                              className: "font-mono text-sm",
                              "data-cy": sel("blockEditor.configPanel.customFieldsSection.fieldKey", { index })
                            }
                          ) }),
                          /* @__PURE__ */ jsx("div", { className: "flex-1", children: /* @__PURE__ */ jsx(
                            Input,
                            {
                              value: field.value,
                              onChange: (e) => handleUpdateCustomField(index, "value", e.target.value),
                              placeholder: tSettings("customFields.valuePlaceholder"),
                              "data-cy": sel("blockEditor.configPanel.customFieldsSection.fieldValue", { index })
                            }
                          ) }),
                          /* @__PURE__ */ jsx(
                            Button,
                            {
                              variant: "ghost",
                              size: "icon",
                              className: "shrink-0 text-muted-foreground hover:text-destructive",
                              onClick: () => handleRemoveCustomField(index),
                              "data-cy": sel("blockEditor.configPanel.customFieldsSection.fieldRemove", { index }),
                              children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4" })
                            }
                          )
                        ] }, index)) }),
                        /* @__PURE__ */ jsxs(
                          Button,
                          {
                            variant: "outline",
                            size: "sm",
                            onClick: handleAddCustomField,
                            className: "w-full",
                            "data-cy": sel("blockEditor.configPanel.customFieldsSection.addButton"),
                            children: [
                              /* @__PURE__ */ jsx(Plus, { className: "h-4 w-4 mr-2" }),
                              tSettings("customFields.add")
                            ]
                          }
                        )
                      ] })
                    }
                  )
                ]
              }
            )
          ] })
        }
      )
    }
  );
}
export {
  ConfigPanel
};
