"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useState, useMemo, useRef } from "react";
import { useTranslations } from "next-intl";
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 { RichTextEditor } from "../../ui/rich-text-editor";
import { ChevronDown, ChevronRight, CalendarIcon } from "lucide-react";
import { cn } from "../../../lib/utils";
import { Switch } from "../../ui/switch";
import { RadioGroup, RadioGroupItem } from "../../ui/radio-group";
import { Calendar } from "../../ui/calendar";
import { Popover, PopoverContent, PopoverTrigger } from "../../ui/popover";
import { Button } from "../../ui/button";
import { format } from "date-fns";
import { ArrayField } from "./array-field";
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 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": `field-${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": `field-${field.name}`
          }
        );
      case "rich-text":
        return /* @__PURE__ */ jsx(
          RichTextEditor,
          {
            value: String(value),
            onChange: (newValue) => handleFieldChange(field.name, newValue),
            placeholder: field.placeholder,
            "data-cy": `field-${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": `field-${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": `field-${field.name}`
          }
        );
      case "select":
        return /* @__PURE__ */ jsxs(
          Select,
          {
            value: String(value),
            onValueChange: (newValue) => handleFieldChange(field.name, newValue),
            children: [
              /* @__PURE__ */ jsx(SelectTrigger, { "data-cy": `field-${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": `field-${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": `field-${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": `field-${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": `field-${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": `field-${field.name}`,
              children: [
                /* @__PURE__ */ jsx(CalendarIcon, { className: "mr-2 h-4 w-4" }),
                value ? format(new Date(String(value)), "PPP") : "Pick a date"
              ]
            }
          ) }),
          /* @__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": `field-${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": `field-${field.name}`
          }
        );
      default:
        return /* @__PURE__ */ jsx(
          Input,
          {
            type: "text",
            value: String(value),
            onChange: (e) => handleFieldChange(field.name, e.target.value),
            placeholder: field.placeholder,
            "data-cy": `field-${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": `array-group-${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__ */ jsxs("span", { className: "text-xs text-primary font-normal", children: [
                  items.length,
                  " ",
                  items.length === 1 ? "item" : "items"
                ] })
              ]
            }
          ),
          !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": `field-group-${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: "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": "dynamic-form", children: [
    ungrouped.map(
      (field) => field.type === "array" ? renderArrayFieldAsGroup(field) : renderFieldWithLabel(field)
    ),
    groups.map((group) => renderGroup(group))
  ] });
}
export {
  DynamicForm
};
