"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useCallback } from "react";
import { useTranslations } from "next-intl";
import { Button } from "../../ui/button";
import { Input } from "../../ui/input";
import { Textarea } from "../../ui/textarea";
import { Label } from "../../ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "../../ui/select";
import { ImageUpload } from "../../ui/image-upload";
import { Card, CardContent, CardHeader } from "../../ui/card";
import { ChevronUp, ChevronDown, Trash2, Plus } from "lucide-react";
function ArrayField({ field, value, onChange }) {
  const t = useTranslations("admin.blockEditor.form");
  const items = Array.isArray(value) ? value : [];
  const itemFields = field.itemFields || [];
  const minItems = field.minItems ?? 0;
  const maxItems = field.maxItems ?? Infinity;
  const canAdd = items.length < maxItems;
  const canRemove = items.length > minItems;
  const createEmptyItem = useCallback(() => {
    const emptyItem = {};
    for (const itemField of itemFields) {
      emptyItem[itemField.name] = itemField.default ?? "";
    }
    return emptyItem;
  }, [itemFields]);
  const handleAddItem = useCallback(() => {
    if (!canAdd) return;
    onChange([...items, createEmptyItem()]);
  }, [items, onChange, canAdd, createEmptyItem]);
  const handleRemoveItem = useCallback((index) => {
    if (!canRemove) return;
    onChange(items.filter((_, i) => i !== index));
  }, [items, onChange, canRemove]);
  const handleMoveUp = useCallback((index) => {
    if (index === 0) return;
    const newItems = [...items];
    [newItems[index - 1], newItems[index]] = [newItems[index], newItems[index - 1]];
    onChange(newItems);
  }, [items, onChange]);
  const handleMoveDown = useCallback((index) => {
    if (index === items.length - 1) return;
    const newItems = [...items];
    [newItems[index], newItems[index + 1]] = [newItems[index + 1], newItems[index]];
    onChange(newItems);
  }, [items, onChange]);
  const handleItemFieldChange = useCallback((itemIndex, fieldName, fieldValue) => {
    const newItems = items.map((item, i) => {
      if (i !== itemIndex) return item;
      return {
        ...item,
        [fieldName]: fieldValue
      };
    });
    onChange(newItems);
  }, [items, onChange]);
  const renderItemField = (itemField, itemIndex, itemValue) => {
    var _a;
    const fieldValue = itemValue[itemField.name] ?? itemField.default ?? "";
    switch (itemField.type) {
      case "text":
        return /* @__PURE__ */ jsx(
          Input,
          {
            type: "text",
            value: String(fieldValue),
            onChange: (e) => handleItemFieldChange(itemIndex, itemField.name, e.target.value),
            placeholder: itemField.placeholder,
            required: itemField.required,
            "data-cy": `array-field-${field.name}-${itemIndex}-${itemField.name}`
          }
        );
      case "textarea":
        return /* @__PURE__ */ jsx(
          Textarea,
          {
            value: String(fieldValue),
            onChange: (e) => handleItemFieldChange(itemIndex, itemField.name, e.target.value),
            placeholder: itemField.placeholder,
            required: itemField.required,
            rows: itemField.rows || 3,
            "data-cy": `array-field-${field.name}-${itemIndex}-${itemField.name}`
          }
        );
      case "url":
        return /* @__PURE__ */ jsx(
          Input,
          {
            type: "url",
            value: String(fieldValue),
            onChange: (e) => handleItemFieldChange(itemIndex, itemField.name, e.target.value),
            placeholder: itemField.placeholder || "https://example.com",
            required: itemField.required,
            "data-cy": `array-field-${field.name}-${itemIndex}-${itemField.name}`
          }
        );
      case "number":
        return /* @__PURE__ */ jsx(
          Input,
          {
            type: "number",
            value: Number(fieldValue),
            onChange: (e) => handleItemFieldChange(itemIndex, itemField.name, Number(e.target.value)),
            placeholder: itemField.placeholder,
            required: itemField.required,
            min: itemField.min,
            max: itemField.max,
            step: itemField.step,
            "data-cy": `array-field-${field.name}-${itemIndex}-${itemField.name}`
          }
        );
      case "select":
        return /* @__PURE__ */ jsxs(
          Select,
          {
            value: String(fieldValue),
            onValueChange: (newValue) => handleItemFieldChange(itemIndex, itemField.name, newValue),
            children: [
              /* @__PURE__ */ jsx(SelectTrigger, { "data-cy": `array-field-${field.name}-${itemIndex}-${itemField.name}`, children: /* @__PURE__ */ jsx(SelectValue, { placeholder: itemField.placeholder }) }),
              /* @__PURE__ */ jsx(SelectContent, { children: (_a = itemField.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(fieldValue) ? fieldValue : fieldValue ? [String(fieldValue)] : [],
            onChange: (newValue) => handleItemFieldChange(itemIndex, itemField.name, newValue[0] || ""),
            maxImages: 1,
            "data-cy": `array-field-${field.name}-${itemIndex}-${itemField.name}`
          }
        );
      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 flex-shrink-0",
              style: { backgroundColor: String(fieldValue || "#000000") },
              children: /* @__PURE__ */ jsx(
                Input,
                {
                  type: "color",
                  value: String(fieldValue || "#000000"),
                  onChange: (e) => handleItemFieldChange(itemIndex, itemField.name, e.target.value),
                  className: "opacity-0 w-full h-full cursor-pointer absolute inset-0",
                  "data-cy": `array-field-${field.name}-${itemIndex}-${itemField.name}`
                }
              )
            }
          ),
          /* @__PURE__ */ jsx(
            Input,
            {
              type: "text",
              value: String(fieldValue || "#000000"),
              onChange: (e) => handleItemFieldChange(itemIndex, itemField.name, e.target.value),
              placeholder: "#000000",
              className: "flex-1 font-mono text-sm"
            }
          )
        ] });
      default:
        return /* @__PURE__ */ jsx(
          Input,
          {
            type: "text",
            value: String(fieldValue),
            onChange: (e) => handleItemFieldChange(itemIndex, itemField.name, e.target.value),
            placeholder: itemField.placeholder,
            "data-cy": `array-field-${field.name}-${itemIndex}-${itemField.name}`
          }
        );
    }
  };
  return /* @__PURE__ */ jsxs("div", { className: "space-y-3", "data-cy": `array-field-${field.name}`, children: [
    items.length === 0 ? /* @__PURE__ */ jsx("div", { className: "text-center py-6 border border-dashed rounded-lg", children: /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("emptyArray") }) }) : /* @__PURE__ */ jsx("div", { className: "space-y-3", children: items.map((item, index) => /* @__PURE__ */ jsxs(Card, { className: "relative", children: [
      /* @__PURE__ */ jsxs(CardHeader, { className: "py-2 px-3 flex flex-row items-center justify-between space-y-0 bg-muted/30", children: [
        /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: t("itemNumber", { number: index + 1 }) }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              variant: "ghost",
              size: "icon",
              className: "h-7 w-7",
              onClick: () => handleMoveUp(index),
              disabled: index === 0,
              "data-cy": `array-field-${field.name}-${index}-move-up`,
              children: /* @__PURE__ */ jsx(ChevronUp, { className: "h-4 w-4" })
            }
          ),
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              variant: "ghost",
              size: "icon",
              className: "h-7 w-7",
              onClick: () => handleMoveDown(index),
              disabled: index === items.length - 1,
              "data-cy": `array-field-${field.name}-${index}-move-down`,
              children: /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4" })
            }
          ),
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              variant: "ghost",
              size: "icon",
              className: "h-7 w-7 text-muted-foreground hover:text-destructive",
              onClick: () => handleRemoveItem(index),
              disabled: !canRemove,
              "data-cy": `array-field-${field.name}-${index}-remove`,
              children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4" })
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsx(CardContent, { className: "p-3 space-y-3", children: itemFields.map((itemField) => /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
        /* @__PURE__ */ jsxs(Label, { className: "text-xs", children: [
          itemField.label,
          itemField.required && /* @__PURE__ */ jsx("span", { className: "text-destructive ml-1", children: "*" })
        ] }),
        renderItemField(itemField, index, item),
        itemField.helpText && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: itemField.helpText })
      ] }, itemField.name)) })
    ] }, index)) }),
    /* @__PURE__ */ jsx("div", { className: "flex items-center justify-between", children: /* @__PURE__ */ jsxs(
      Button,
      {
        type: "button",
        variant: "outline",
        size: "sm",
        onClick: handleAddItem,
        disabled: !canAdd,
        className: "w-full",
        "data-cy": `array-field-${field.name}-add`,
        children: [
          /* @__PURE__ */ jsx(Plus, { className: "h-4 w-4 mr-2" }),
          t("addItem")
        ]
      }
    ) }),
    maxItems !== Infinity && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground text-center", children: t("itemCount", { current: items.length, max: maxItems }) })
  ] });
}
export {
  ArrayField
};
