"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { Input } from "../ui/input";
import { Textarea } from "../ui/textarea";
import { Switch } from "../ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
import { RadioGroup, RadioGroupItem } from "../ui/radio-group";
import { Badge } from "../ui/badge";
import { Card, CardContent } from "../ui/card";
import { Label } from "../ui/label";
import { Slider } from "../ui/slider";
import { MultiSelect } from "../ui/multi-select";
import { TagsInput } from "../ui/tags-input";
import { Combobox } from "../ui/combobox";
import { Rating } from "../ui/rating";
import { PhoneInput } from "../ui/phone-input";
import { FileUpload } from "../ui/file-upload";
import { ImageUpload } from "../ui/image-upload";
import { VideoUpload } from "../ui/video-upload";
import { AudioUpload } from "../ui/audio-upload";
import { TimezoneSelect } from "../ui/timezone-select";
import { CurrencySelect } from "../ui/currency-select";
import { CountrySelect } from "../ui/country-select";
import { AddressInput } from "../ui/address-input";
import { SimpleRelationSelect } from "../ui/simple-relation-select";
import { RelationDisplay } from "../ui/relation-display";
import { RichTextEditor } from "../ui/rich-text-editor";
import { UserDisplay } from "../ui/user-display";
import { UserSelect } from "../ui/user-select";
import { ButtonGroup } from "../ui/button-group";
import { DoubleRange } from "../ui/double-range";
function formatDisplayValue(value, field) {
  if (value === null || value === void 0) {
    return "-";
  }
  switch (field.type) {
    case "text":
    case "textarea":
    case "email":
    case "url":
    case "phone":
    case "timezone":
    case "currency":
    case "country":
      return String(value || "");
    case "number":
      return typeof value === "number" ? value.toLocaleString() : String(value || "");
    case "boolean":
      return value ? "S\xED" : "No";
    case "date":
      return value ? new Date(value).toLocaleDateString() : "";
    case "datetime":
      return value ? new Date(value).toLocaleString() : "";
    case "json":
      return typeof value === "object" ? JSON.stringify(value, null, 2) : String(value || "");
    case "select":
    case "radio":
    case "buttongroup":
    case "combobox":
      if (field.options) {
        const option = field.options.find((opt) => opt.value === value);
        return option ? option.label : String(value || "");
      }
      return String(value || "");
    case "multiselect":
      if (Array.isArray(value) && field.options) {
        return value.map((v) => {
          var _a, _b;
          return ((_b = (_a = field.options) == null ? void 0 : _a.find((opt) => opt.value === v)) == null ? void 0 : _b.label) || v;
        }).join(", ");
      }
      return String(value || "");
    case "tags":
      return Array.isArray(value) ? value.join(", ") : String(value || "");
    case "rating":
      return typeof value === "number" ? `${value}/5 \u2B50` : String(value || "");
    case "range":
      return typeof value === "number" ? String(value) : String(value || "");
    case "doublerange":
      if (Array.isArray(value) && value.length === 2) {
        return `${value[0]} - ${value[1]}`;
      }
      return String(value || "");
    case "address":
      if (typeof value === "object" && value !== null) {
        const addr = value;
        return addr.fullAddress || [addr.street, addr.city, addr.state, addr.country].filter(Boolean).join(", ");
      }
      return String(value || "");
    case "file":
    case "image":
    case "video":
    case "audio":
      if (Array.isArray(value)) {
        return `${value.length} archivo${value.length !== 1 ? "s" : ""}`;
      }
      return String(value || "");
    case "relation":
    case "relation-multi":
      return String(value || "-");
    case "user":
      if (Array.isArray(value)) {
        return value.map(
          (user) => `${user.firstName} ${user.lastName || ""}`.trim()
        ).join(", ");
      }
      return String(value || "");
    case "markdown":
    case "richtext":
    case "code":
      return String(value || "");
    default:
      return String(value || "");
  }
}
function renderFormField(field, value, onChange, error, disabled, required, testId, context) {
  var _a, _b, _c, _d;
  if (field.name === "language") {
  }
  const baseProps = {
    id: `field-${field.name}`,
    disabled,
    "data-testid": testId,
    "aria-describedby": error ? `${field.name}-error` : void 0,
    "aria-invalid": !!error
  };
  switch (field.type) {
    // Basic text inputs
    case "text":
    case "email":
    case "url":
      return /* @__PURE__ */ jsx(
        Input,
        {
          ...baseProps,
          type: field.type === "email" ? "email" : "text",
          value: String(value || ""),
          onChange: (e) => onChange(e.target.value),
          placeholder: field.display.placeholder,
          required
        }
      );
    case "textarea":
      return /* @__PURE__ */ jsx(
        Textarea,
        {
          ...baseProps,
          value: String(value || ""),
          onChange: (e) => onChange(e.target.value),
          placeholder: field.display.placeholder,
          required,
          className: "min-h-[100px]"
        }
      );
    case "number":
      return /* @__PURE__ */ jsx(
        Input,
        {
          ...baseProps,
          type: "number",
          value: String(value || ""),
          onChange: (e) => onChange(Number(e.target.value)),
          placeholder: field.display.placeholder,
          required
        }
      );
    case "boolean":
      return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: `field-${field.name}`, className: "text-sm font-medium", children: field.display.label }),
        /* @__PURE__ */ jsx("div", { className: "flex justify-start", children: /* @__PURE__ */ jsx(
          Switch,
          {
            ...baseProps,
            checked: Boolean(value),
            onCheckedChange: (checked) => onChange(checked)
          }
        ) })
      ] });
    case "date":
      return /* @__PURE__ */ jsx(
        Input,
        {
          ...baseProps,
          type: "date",
          value: value ? new Date(value).toISOString().split("T")[0] : "",
          onChange: (e) => onChange(e.target.value),
          required
        }
      );
    case "datetime":
      return /* @__PURE__ */ jsx(
        Input,
        {
          ...baseProps,
          type: "datetime-local",
          value: value ? new Date(value).toISOString().slice(0, 16) : "",
          onChange: (e) => onChange(e.target.value),
          required
        }
      );
    case "json":
      return /* @__PURE__ */ jsx(
        Textarea,
        {
          ...baseProps,
          value: typeof value === "object" ? JSON.stringify(value, null, 2) : String(value || ""),
          onChange: (e) => {
            try {
              const parsed = JSON.parse(e.target.value);
              onChange(parsed);
            } catch {
              onChange(e.target.value);
            }
          },
          placeholder: field.display.placeholder || "Enter valid JSON...",
          required,
          className: "min-h-[120px] font-mono text-sm"
        }
      );
    // Selection types
    case "select":
      return /* @__PURE__ */ jsxs(
        Select,
        {
          value: String(value || ""),
          onValueChange: (newValue) => onChange(newValue),
          disabled,
          required,
          children: [
            /* @__PURE__ */ jsx(SelectTrigger, { ...baseProps, children: /* @__PURE__ */ jsx(SelectValue, { placeholder: field.display.placeholder }) }),
            /* @__PURE__ */ jsx(SelectContent, { children: (_a = field.options) == null ? void 0 : _a.map((option) => /* @__PURE__ */ jsx(
              SelectItem,
              {
                value: String(option.value),
                disabled: option.disabled,
                children: option.label
              },
              String(option.value)
            )) })
          ]
        }
      );
    case "multiselect":
      return /* @__PURE__ */ jsx(
        MultiSelect,
        {
          options: field.options || [],
          value: Array.isArray(value) ? value : [],
          onChange,
          placeholder: field.display.placeholder,
          disabled
        }
      );
    case "radio":
      return /* @__PURE__ */ jsx(
        RadioGroup,
        {
          value: String(value || ""),
          onValueChange: onChange,
          disabled,
          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),
                disabled: option.disabled
              }
            ),
            /* @__PURE__ */ jsx(Label, { className: "text-sm", children: option.label })
          ] }, String(option.value)))
        }
      );
    case "buttongroup":
      return /* @__PURE__ */ jsx(
        ButtonGroup,
        {
          options: field.options || [],
          value,
          onChange,
          disabled
        }
      );
    case "tags":
      return /* @__PURE__ */ jsx(
        TagsInput,
        {
          value: Array.isArray(value) ? value : [],
          onChange,
          placeholder: field.display.placeholder,
          disabled
        }
      );
    case "combobox":
      return /* @__PURE__ */ jsx(
        Combobox,
        {
          options: field.options || [],
          value,
          onChange,
          placeholder: field.display.placeholder,
          disabled,
          clearable: !required
        }
      );
    // Specialized inputs
    case "phone":
      return /* @__PURE__ */ jsx(
        PhoneInput,
        {
          value: String(value || ""),
          onChange,
          placeholder: field.display.placeholder,
          disabled
        }
      );
    case "rating":
      return /* @__PURE__ */ jsx(
        Rating,
        {
          value: typeof value === "number" ? value : 0,
          onChange,
          readonly: disabled,
          showValue: true
        }
      );
    case "range":
      return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx(
          Slider,
          {
            value: [typeof value === "number" ? value : 0],
            onValueChange: (values) => onChange(values[0]),
            disabled,
            max: 100,
            step: 1
          }
        ),
        /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground text-center", children: [
          "Valor: ",
          typeof value === "number" ? value : 0
        ] })
      ] });
    case "doublerange":
      return /* @__PURE__ */ jsx(
        DoubleRange,
        {
          value: Array.isArray(value) && value.length === 2 ? value : void 0,
          onChange,
          disabled,
          min: 0,
          max: 100,
          step: 1
        }
      );
    // Location & data selectors
    case "timezone":
      return /* @__PURE__ */ jsx(
        TimezoneSelect,
        {
          value,
          onChange,
          placeholder: field.display.placeholder,
          disabled
        }
      );
    case "currency":
      return /* @__PURE__ */ jsx(
        CurrencySelect,
        {
          value,
          onChange,
          placeholder: field.display.placeholder,
          disabled
        }
      );
    case "country":
      return /* @__PURE__ */ jsx(
        CountrySelect,
        {
          value,
          onChange,
          placeholder: field.display.placeholder,
          disabled
        }
      );
    case "address":
      return /* @__PURE__ */ jsx(
        AddressInput,
        {
          value: value || { street: "", city: "", state: "", zipCode: "", country: "" },
          onChange,
          disabled,
          layout: "stacked"
        }
      );
    // Media types
    case "file":
      return /* @__PURE__ */ jsx(
        FileUpload,
        {
          value: Array.isArray(value) ? value : [],
          onChange,
          disabled,
          multiple: true
        }
      );
    case "image":
      return /* @__PURE__ */ jsx(
        ImageUpload,
        {
          value: Array.isArray(value) ? value : [],
          onChange,
          disabled,
          multiple: true
        }
      );
    case "video":
      return /* @__PURE__ */ jsx(
        VideoUpload,
        {
          value: Array.isArray(value) ? value : [],
          onChange,
          disabled,
          multiple: true
        }
      );
    case "audio":
      return /* @__PURE__ */ jsx(
        AudioUpload,
        {
          value: Array.isArray(value) ? value : [],
          onChange,
          disabled,
          multiple: true
        }
      );
    // Relationship types
    case "relation":
    case "relation-multi":
      const relationConfig = field.relation;
      if (!(relationConfig == null ? void 0 : relationConfig.entity)) {
        console.error("Relation field missing entity configuration:", field.name);
        return /* @__PURE__ */ jsx("div", { children: "Error: Relation configuration missing" });
      }
      const relationEntityType = relationConfig.entity;
      const titleField = relationConfig.titleField;
      const isMultiple = field.type === "relation-multi";
      const formData = context == null ? void 0 : context.formData;
      const dependsOnParent = Boolean(relationConfig.parentId);
      const parentFieldName = relationConfig.parentId;
      const parentValue = parentFieldName ? formData == null ? void 0 : formData[parentFieldName] : void 0;
      const parentIdForRelation = parentValue;
      let processedValue = null;
      if (isMultiple) {
        if (typeof value === "string" && value) {
          try {
            processedValue = JSON.parse(value);
          } catch {
            processedValue = [];
          }
        } else if (Array.isArray(value)) {
          processedValue = value;
        } else {
          processedValue = [];
        }
      } else {
        processedValue = typeof value === "string" ? value : value ? String(value) : null;
      }
      return /* @__PURE__ */ jsx(
        SimpleRelationSelect,
        {
          value: processedValue || void 0,
          onChange: (newValue) => {
            if (isMultiple) {
              onChange(newValue);
            } else {
              onChange(newValue);
            }
          },
          entityType: relationEntityType,
          titleField,
          multiple: isMultiple,
          disabled: disabled || dependsOnParent && !parentValue,
          placeholder: dependsOnParent && !parentValue ? `Selecciona ${parentFieldName == null ? void 0 : parentFieldName.replace("Id", "").toLowerCase()} primero` : field.display.placeholder || `Seleccionar ${((_c = field.display.label) == null ? void 0 : _c.toLowerCase()) || relationEntityType}...`,
          parentId: parentIdForRelation,
          userFiltered: relationConfig.userFiltered,
          teamId: context == null ? void 0 : context.teamId
        }
      );
    // Property-based relationship types
    case "relation-prop":
    case "relation-prop-multi":
      const propRelationConfig = field.relation;
      if (!(propRelationConfig == null ? void 0 : propRelationConfig.entity) || !(propRelationConfig == null ? void 0 : propRelationConfig.prop)) {
        console.error("Property relation field missing entity or prop configuration:", field.name);
        return /* @__PURE__ */ jsx("div", { children: "Error: Property relation configuration missing" });
      }
      const propEntityType = propRelationConfig.entity;
      const propField = propRelationConfig.prop;
      const propIsMultiple = field.type === "relation-prop-multi";
      const propFormData = context == null ? void 0 : context.formData;
      const propDependsOnParent = Boolean(propRelationConfig.parentId);
      const propParentFieldName = propRelationConfig.parentId;
      const propParentValue = propParentFieldName ? propFormData == null ? void 0 : propFormData[propParentFieldName] : void 0;
      const propParentIdForRelation = propParentValue;
      let propProcessedValue = null;
      if (propIsMultiple) {
        if (typeof value === "string" && value) {
          try {
            propProcessedValue = JSON.parse(value);
          } catch {
            propProcessedValue = [];
          }
        } else if (Array.isArray(value)) {
          propProcessedValue = value;
        } else {
          propProcessedValue = [];
        }
      } else {
        propProcessedValue = typeof value === "string" ? value : value ? String(value) : null;
      }
      return /* @__PURE__ */ jsx(
        SimpleRelationSelect,
        {
          value: propProcessedValue || void 0,
          onChange: (newValue) => {
            if (propIsMultiple) {
              onChange(newValue);
            } else {
              onChange(newValue);
            }
          },
          entityType: propEntityType,
          propField,
          usePropertyMode: true,
          propertyOptions: (propRelationConfig.options || []).map((opt) => ({
            value: String(opt.value),
            label: opt.label
          })),
          multiple: propIsMultiple,
          disabled: disabled || propDependsOnParent && !propParentValue,
          placeholder: propDependsOnParent && !propParentValue ? `Selecciona ${propParentFieldName == null ? void 0 : propParentFieldName.replace("Id", "").toLowerCase()} primero` : field.display.placeholder || `Seleccionar ${(_d = field.display.label) == null ? void 0 : _d.toLowerCase()}...`,
          parentId: propParentIdForRelation,
          userFiltered: propRelationConfig.userFiltered,
          teamId: context == null ? void 0 : context.teamId
        }
      );
    case "user":
      const userValue = (() => {
        if (!value) return [];
        if (Array.isArray(value)) return value;
        if (typeof value === "string") {
          return [{ id: value, firstName: "", email: "" }];
        }
        return [];
      })();
      return /* @__PURE__ */ jsx(
        UserSelect,
        {
          value: userValue,
          onChange,
          disabled,
          multiple: false,
          placeholder: field.display.placeholder,
          teamId: context == null ? void 0 : context.teamId
        }
      );
    // Rich text editor with WYSIWYG toolbar
    case "richtext":
      return /* @__PURE__ */ jsx(
        RichTextEditor,
        {
          value: String(value || ""),
          onChange,
          placeholder: field.display.placeholder || "Enter rich text content...",
          disabled,
          "data-cy": testId
        }
      );
    // Text editors (simplified for now)
    case "markdown":
    case "code":
      return /* @__PURE__ */ jsx(
        Textarea,
        {
          ...baseProps,
          value: String(value || ""),
          onChange: (e) => onChange(e.target.value),
          placeholder: field.display.placeholder || `Ingresa ${field.type}...`,
          required,
          className: field.type === "code" ? "min-h-[150px] font-mono text-sm" : "min-h-[150px]"
        }
      );
    default:
      return /* @__PURE__ */ jsx(
        Input,
        {
          ...baseProps,
          value: String(value || ""),
          onChange: (e) => onChange(e.target.value),
          placeholder: field.display.placeholder,
          required
        }
      );
  }
}
function renderDisplayField(field, value, mode, context) {
  if (field.type === "user") {
    const userId = Array.isArray(value) && value.length > 0 ? typeof value[0] === "object" ? value[0].id : value[0] : typeof value === "object" && value !== null ? value.id : value;
    const userDisplay = /* @__PURE__ */ jsx(
      UserDisplay,
      {
        value: userId || null,
        teamId: context == null ? void 0 : context.teamId,
        showEmail: mode === "display"
      }
    );
    if (mode === "list") {
      return userDisplay;
    }
    return /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
      /* @__PURE__ */ jsx(Label, { className: "text-[11px] font-medium uppercase tracking-wider text-muted-foreground", children: field.display.label }),
      /* @__PURE__ */ jsx("div", { className: "text-base", children: userDisplay })
    ] });
  }
  if (field.type === "relation" || field.type === "relation-multi") {
    const relationConfig = field.relation;
    if (relationConfig == null ? void 0 : relationConfig.entity) {
      const parentIdValue = relationConfig.parentId && (context == null ? void 0 : context.formData) ? context.formData[relationConfig.parentId] : void 0;
      const relationDisplay = /* @__PURE__ */ jsx(
        RelationDisplay,
        {
          value,
          entityType: relationConfig.entity,
          titleField: relationConfig.titleField,
          parentId: parentIdValue,
          multiple: field.type === "relation-multi",
          teamId: context == null ? void 0 : context.teamId
        }
      );
      if (mode === "list") {
        return relationDisplay;
      }
      return /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
        /* @__PURE__ */ jsx(Label, { className: "text-[11px] font-medium uppercase tracking-wider text-muted-foreground", children: field.display.label }),
        /* @__PURE__ */ jsx("div", { className: "text-base", children: relationDisplay })
      ] });
    }
  }
  const formattedValue = formatDisplayValue(value, field);
  if (mode === "list") {
    if (field.type === "boolean") {
      return /* @__PURE__ */ jsx(
        Badge,
        {
          variant: value ? "default" : "secondary",
          className: `text-xs ${value ? "bg-green-500 hover:bg-green-600" : "bg-gray-500 hover:bg-gray-600"}`,
          children: formattedValue
        }
      );
    }
    if (field.type === "select" && field.options) {
      const option = field.options.find((opt) => opt.value === value);
      return /* @__PURE__ */ jsx(
        Badge,
        {
          variant: "outline",
          className: "text-xs",
          style: { backgroundColor: option == null ? void 0 : option.color },
          children: formattedValue
        }
      );
    }
    return /* @__PURE__ */ jsx("span", { className: "text-sm truncate max-w-[200px]", title: formattedValue, children: formattedValue });
  }
  return /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
    /* @__PURE__ */ jsx(Label, { className: "text-[11px] font-medium uppercase tracking-wider text-muted-foreground", children: field.display.label }),
    field.type === "json" ? /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsx("pre", { className: "text-xs overflow-auto max-h-40", children: formattedValue }) }) }) : field.type === "textarea" ? /* @__PURE__ */ jsx("p", { className: "text-base leading-relaxed whitespace-pre-wrap", children: formattedValue }) : field.type === "url" ? /* @__PURE__ */ jsx(
      "a",
      {
        href: String(value),
        target: "_blank",
        rel: "noopener noreferrer",
        className: "text-base underline underline-offset-2 hover:no-underline",
        children: formattedValue
      }
    ) : field.type === "email" ? /* @__PURE__ */ jsx(
      "a",
      {
        href: `mailto:${value}`,
        className: "text-base underline underline-offset-2 hover:no-underline",
        children: formattedValue
      }
    ) : /* @__PURE__ */ jsx("p", { className: "text-base", children: formattedValue })
  ] });
}
function EntityFieldRenderer({
  field,
  value,
  onChange,
  mode,
  error,
  disabled = false,
  required,
  className,
  testId,
  context
}) {
  if (mode === "form") {
    if (!onChange) {
      throw new Error("onChange is required for form mode");
    }
    return /* @__PURE__ */ jsxs("div", { className: `space-y-2 ${className || ""}`, children: [
      field.type !== "boolean" && /* @__PURE__ */ jsxs(Label, { htmlFor: `field-${field.name}`, className: "text-sm font-medium", children: [
        field.display.label,
        required && /* @__PURE__ */ jsx("span", { className: "text-red-500 ml-1", children: "*" })
      ] }),
      field.display.description && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: field.display.description }),
      renderFormField(field, value, onChange, error, disabled, required, testId, context),
      error && /* @__PURE__ */ jsx(
        "p",
        {
          id: `${field.name}-error`,
          className: "text-xs text-red-600",
          role: "alert",
          children: error
        }
      )
    ] });
  }
  return /* @__PURE__ */ jsx("div", { className, children: renderDisplayField(field, value, mode, context) });
}
export {
  EntityFieldRenderer
};
