"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useTranslations } from "next-intl";
import { useQuery } from "@tanstack/react-query";
import { sel } from "../../../lib/test/index.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 { ScrollArea } from "../../ui/scroll-area.js";
import { Checkbox } from "../../ui/checkbox.js";
import { FileText, Image, Tag, Loader2 } from "lucide-react";
import { SimpleRelationSelect } from "../../ui/simple-relation-select.js";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "../../ui/select.js";
function EntityFieldsSidebar({
  entityConfig,
  fields,
  onChange,
  selectedCategories = [],
  onCategoryToggle
}) {
  var _a, _b, _c;
  const t = useTranslations("admin.builder");
  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 renderField = (fieldName) => {
    var _a2;
    const value = fields[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 = fields[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) => onChange(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) => onChange(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);
    }
    if ((fieldConfig == null ? void 0 : fieldConfig.type) === "textarea") {
      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) => onChange(fieldName, e.target.value),
            placeholder: fieldConfig.placeholder || t("placeholders.excerpt"),
            rows: fieldConfig.rows || 4,
            className: "resize-none",
            "data-cy": sel("blockEditor.entityFieldsPanel.field", { name: fieldName })
          }
        )
      ] }, 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) => onChange(fieldName, e.target.value),
            placeholder: t("placeholders.excerpt"),
            rows: 4,
            className: "resize-none",
            "data-cy": sel("blockEditor.entityFieldsPanel.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) => onChange(fieldName, e.target.value),
            placeholder: t("placeholders.imageUrl"),
            "data-cy": sel("blockEditor.entityFieldsPanel.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) => onChange(fieldName, e.target.value),
          "data-cy": sel("blockEditor.entityFieldsPanel.field", { name: fieldName })
        }
      )
    ] }, fieldName);
  };
  const currentCategories = fields.categories || [];
  const handleCategoryClick = (categoryId) => {
    const newCategories = currentCategories.includes(categoryId) ? currentCategories.filter((id) => id !== categoryId) : [...currentCategories, categoryId];
    onChange("categories", newCategories);
  };
  return /* @__PURE__ */ jsxs("div", { className: "flex h-full flex-col bg-card", "data-cy": sel("blockEditor.entityFieldsPanel.container"), children: [
    /* @__PURE__ */ jsxs("div", { className: "border-b p-4", children: [
      /* @__PURE__ */ jsx("h3", { className: "font-semibold text-foreground", children: t("sidebar.fieldsTitle") }),
      /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("sidebar.fieldsDescription") })
    ] }),
    /* @__PURE__ */ jsx(ScrollArea, { className: "flex-1 p-4", children: /* @__PURE__ */ jsxs("div", { className: "space-y-6", 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", "data-cy": sel("blockEditor.entityFieldsPanel.categoryList"), 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),
            "data-cy": sel("blockEditor.entityFieldsPanel.categoryItem", { slug: item.slug }),
            children: [
              /* @__PURE__ */ jsx(
                Checkbox,
                {
                  checked: currentCategories.includes(item.id),
                  onCheckedChange: () => handleCategoryClick(item.id),
                  "data-cy": sel("blockEditor.entityFieldsPanel.categoryCheckbox", { slug: item.slug })
                }
              ),
              /* @__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,
              "data-cy": sel("blockEditor.entityFieldsPanel.categoryBadge", { slug: cat.slug }),
              children: [
                cat.name,
                " \xD7"
              ]
            },
            cat.id
          ) : null;
        }) })
      ] }),
      sidebarFields.length === 0 && !taxonomiesEnabled && /* @__PURE__ */ jsx("div", { className: "text-center py-8 text-muted-foreground", children: /* @__PURE__ */ jsx("p", { children: t("sidebar.noFields") }) })
    ] }) })
  ] });
}
export {
  EntityFieldsSidebar
};
