"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useState, useCallback, useEffect } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../ui/card.js";
import { Button } from "../ui/button.js";
import { Alert, AlertDescription } from "../ui/alert.js";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs.js";
import { Badge } from "../ui/badge.js";
import {
  Loader2,
  Save,
  AlertCircle,
  Plus,
  Trash2
} from "lucide-react";
import { EntityFieldRenderer } from "./EntityFieldRenderer.js";
import { sel } from "../../lib/test/index.js";
function validateFormData(data, entityConfig) {
  const errors = {};
  entityConfig.fields.forEach((field) => {
    if (!field.display.showInForm) return;
    const value = data[field.name];
    if (field.required && (!value || typeof value === "string" && !value.trim())) {
      errors[field.name] = `${field.display.label} is required`;
      return;
    }
    if (value !== void 0 && value !== null && value !== "") {
      switch (field.type) {
        case "email":
          const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
          if (!emailRegex.test(String(value))) {
            errors[field.name] = "Please enter a valid email address";
          }
          break;
        case "url":
          try {
            let urlValue = String(value).trim();
            if (!/^https?:\/\//i.test(urlValue)) {
              urlValue = `https://${urlValue}`;
            }
            new URL(urlValue);
          } catch {
            errors[field.name] = "Please enter a valid URL";
          }
          break;
        case "number":
          if (isNaN(Number(value))) {
            errors[field.name] = "Please enter a valid number";
          }
          break;
        case "json":
          if (typeof value === "string") {
            try {
              JSON.parse(value);
            } catch {
              errors[field.name] = "Please enter valid JSON";
            }
          }
          break;
      }
    }
  });
  return errors;
}
function generateTestIds(entityName) {
  return {
    form: `${entityName}-form`,
    field: (fieldName) => `${entityName}-field-${fieldName}`,
    submit: `${entityName}-submit`,
    childSection: (childName) => `${entityName}-child-${childName}`,
    childAdd: (childName) => `${entityName}-${childName}-add`
  };
}
function EntityForm({
  entityConfig,
  initialData = {},
  mode,
  onSubmit,
  onChange,
  isLoading = false,
  error = null,
  validationErrors = {},
  enableChildEntities = false,
  childData = {},
  onChildAdd,
  onChildDelete,
  className,
  disabledFields = [],
  hiddenFields = [],
  teamId
}) {
  const [formData, setFormData] = useState(() => {
    const initial = {};
    entityConfig.fields.forEach((field) => {
      if (!field.display.showInForm) return;
      if (field.name in initialData) {
        initial[field.name] = initialData[field.name];
      } else if (field.defaultValue !== void 0) {
        initial[field.name] = field.defaultValue;
      } else {
        switch (field.type) {
          case "boolean":
            initial[field.name] = false;
            break;
          case "multiselect":
          case "tags":
            initial[field.name] = [];
            break;
          case "number":
            initial[field.name] = "";
            break;
          default:
            initial[field.name] = "";
        }
      }
    });
    return initial;
  });
  const [localValidationErrors, setLocalValidationErrors] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [activeTab, setActiveTab] = useState("main");
  const testIds = generateTestIds(entityConfig.slug);
  useEffect(() => {
    if (Object.keys(initialData).length > 0) {
      setFormData((prev) => ({ ...prev, ...initialData }));
    }
  }, [initialData]);
  useEffect(() => {
    onChange == null ? void 0 : onChange(formData);
  }, [formData, onChange]);
  const formFields = entityConfig.fields.filter((field) => field.display.showInForm).filter((field) => !hiddenFields.includes(field.name)).sort((a, b) => a.display.order - b.display.order);
  const childEntities = enableChildEntities && entityConfig.childEntities ? Object.entries(entityConfig.childEntities).filter(([, config]) => config.showInParentView) : [];
  const handleFieldChange = useCallback((fieldName, value) => {
    setFormData((prev) => {
      const newFormData = { ...prev, [fieldName]: value };
      const dependentFields = entityConfig.fields.filter(
        (field) => {
          var _a;
          return ((_a = field.relation) == null ? void 0 : _a.parentId) === fieldName;
        }
      );
      dependentFields.forEach((field) => {
        if (field.type === "relation-multi") {
          newFormData[field.name] = [];
        } else {
          newFormData[field.name] = null;
        }
      });
      return newFormData;
    });
    if (localValidationErrors[fieldName]) {
      setLocalValidationErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors[fieldName];
        return newErrors;
      });
    }
  }, [localValidationErrors, entityConfig.fields]);
  const handleSubmit = useCallback(async (e) => {
    e.preventDefault();
    const errors = validateFormData(formData, entityConfig);
    const allErrors2 = { ...errors, ...validationErrors };
    if (Object.keys(allErrors2).length > 0) {
      setLocalValidationErrors(allErrors2);
      return;
    }
    setIsSubmitting(true);
    try {
      await onSubmit(formData);
    } catch (err) {
      console.error("Form submission failed:", err);
    } finally {
      setIsSubmitting(false);
    }
  }, [formData, entityConfig, validationErrors, onSubmit]);
  const allErrors = { ...localValidationErrors, ...validationErrors };
  const hasErrors = Object.keys(allErrors).length > 0;
  return /* @__PURE__ */ jsxs("div", { className: `space-y-6 ${className || ""}`, children: [
    error && /* @__PURE__ */ jsxs(Alert, { variant: "destructive", children: [
      /* @__PURE__ */ jsx(AlertCircle, { className: "h-4 w-4" }),
      /* @__PURE__ */ jsx(AlertDescription, { children: error })
    ] }),
    /* @__PURE__ */ jsxs(
      "form",
      {
        onSubmit: handleSubmit,
        "data-testid": testIds.form,
        "data-cy": sel("entities.form.container", { slug: entityConfig.slug }),
        className: "space-y-6",
        children: [
          childEntities.length > 0 ? /* @__PURE__ */ jsxs(Tabs, { value: activeTab, onValueChange: setActiveTab, className: "space-y-6", children: [
            /* @__PURE__ */ jsxs(TabsList, { className: "grid grid-cols-2 lg:grid-cols-4", children: [
              /* @__PURE__ */ jsxs(TabsTrigger, { value: "main", children: [
                "Details",
                hasErrors && /* @__PURE__ */ jsx(Badge, { variant: "destructive", className: "ml-2 h-5 w-5 p-0 text-xs", children: "!" })
              ] }),
              childEntities.map(([childName, childConfig]) => {
                var _a;
                return /* @__PURE__ */ jsxs(TabsTrigger, { value: childName, children: [
                  childConfig.display.title,
                  ((_a = childData[childName]) == null ? void 0 : _a.length) ? /* @__PURE__ */ jsx(Badge, { variant: "outline", className: "ml-2", children: childData[childName].length }) : null
                ] }, childName);
              })
            ] }),
            /* @__PURE__ */ jsx(TabsContent, { value: "main", children: /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsx(CardContent, { className: "p-6", children: /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 md:grid-cols-12 gap-6", children: formFields.map((field) => {
              const getColumnSpanClass = (width) => {
                if (!width) return "md:col-span-6";
                switch (width) {
                  case 1:
                    return "md:col-span-1";
                  case 2:
                    return "md:col-span-2";
                  case 3:
                    return "md:col-span-3";
                  case 4:
                    return "md:col-span-4";
                  case 5:
                    return "md:col-span-5";
                  case 6:
                    return "md:col-span-6";
                  case 7:
                    return "md:col-span-7";
                  case 8:
                    return "md:col-span-8";
                  case 9:
                    return "md:col-span-9";
                  case 10:
                    return "md:col-span-10";
                  case 11:
                    return "md:col-span-11";
                  case 12:
                    return "md:col-span-12";
                  default:
                    return "md:col-span-12";
                }
              };
              return /* @__PURE__ */ jsx(
                "div",
                {
                  className: getColumnSpanClass(field.display.columnWidth),
                  "data-cy": sel("entities.form.field", { slug: entityConfig.slug, name: field.name }),
                  children: /* @__PURE__ */ jsx(
                    EntityFieldRenderer,
                    {
                      field,
                      value: formData[field.name],
                      onChange: (value) => handleFieldChange(field.name, value),
                      mode: "form",
                      error: allErrors[field.name],
                      disabled: isSubmitting || field.api.readOnly || disabledFields.includes(field.name),
                      required: field.required,
                      testId: testIds.field(field.name),
                      context: {
                        entityType: entityConfig.slug,
                        formData,
                        teamId
                      }
                    }
                  )
                },
                field.name
              );
            }) }) }) }) }),
            childEntities.map(([childName, childConfig]) => {
              var _a;
              return /* @__PURE__ */ jsx(TabsContent, { value: childName, className: "space-y-6", children: /* @__PURE__ */ jsxs(Card, { children: [
                /* @__PURE__ */ jsxs(CardHeader, { children: [
                  /* @__PURE__ */ jsx(CardTitle, { children: childConfig.display.title }),
                  childConfig.display.description && /* @__PURE__ */ jsx(CardDescription, { children: childConfig.display.description })
                ] }),
                /* @__PURE__ */ jsx(CardContent, { children: /* @__PURE__ */ jsxs(
                  "div",
                  {
                    className: "space-y-4",
                    "data-testid": testIds.childSection(childName),
                    children: [
                      ((_a = childData[childName]) == null ? void 0 : _a.length) ? /* @__PURE__ */ jsx("div", { className: "space-y-3", children: childData[childName].map((item, index) => /* @__PURE__ */ jsx(Card, { className: "border-dashed", children: /* @__PURE__ */ jsxs(CardContent, { className: "pt-6", children: [
                        /* @__PURE__ */ jsxs("div", { className: "flex justify-between items-start mb-4", children: [
                          /* @__PURE__ */ jsxs("h4", { className: "font-medium", children: [
                            "Item ",
                            index + 1
                          ] }),
                          onChildDelete && /* @__PURE__ */ jsx(
                            Button,
                            {
                              type: "button",
                              variant: "ghost",
                              size: "sm",
                              onClick: () => onChildDelete(childName, String(item.id)),
                              className: "text-destructive hover:text-destructive",
                              children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4" })
                            }
                          )
                        ] }),
                        /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-4", children: childConfig.fields.map((field) => /* @__PURE__ */ jsx(
                          EntityFieldRenderer,
                          {
                            field: {
                              ...field,
                              api: {
                                searchable: false,
                                sortable: true,
                                readOnly: false
                              },
                              display: field.display || {
                                label: field.name,
                                description: `${field.name} field`,
                                showInList: true,
                                showInDetail: true,
                                showInForm: true,
                                order: 1
                              }
                            },
                            value: item[field.name],
                            mode: "display"
                          },
                          field.name
                        )) })
                      ] }) }, String(item.id) || index)) }) : /* @__PURE__ */ jsx("div", { className: "text-center py-8 text-muted-foreground", children: /* @__PURE__ */ jsxs("p", { children: [
                        "No ",
                        childConfig.display.title.toLowerCase(),
                        " added yet"
                      ] }) }),
                      onChildAdd && /* @__PURE__ */ jsxs(
                        Button,
                        {
                          type: "button",
                          variant: "outline",
                          onClick: () => onChildAdd(childName, {}),
                          "data-testid": testIds.childAdd(childName),
                          children: [
                            /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4" }),
                            "Add ",
                            childConfig.display.title.slice(0, -1),
                            " "
                          ]
                        }
                      )
                    ]
                  }
                ) })
              ] }) }, childName);
            })
          ] }) : (
            /* Single card layout for entities without children */
            /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsx(CardContent, { className: "p-6", children: /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 md:grid-cols-12 gap-6", children: formFields.map((field) => {
              const getColumnSpanClass = (width) => {
                if (!width) return "md:col-span-6";
                switch (width) {
                  case 1:
                    return "md:col-span-1";
                  case 2:
                    return "md:col-span-2";
                  case 3:
                    return "md:col-span-3";
                  case 4:
                    return "md:col-span-4";
                  case 5:
                    return "md:col-span-5";
                  case 6:
                    return "md:col-span-6";
                  case 7:
                    return "md:col-span-7";
                  case 8:
                    return "md:col-span-8";
                  case 9:
                    return "md:col-span-9";
                  case 10:
                    return "md:col-span-10";
                  case 11:
                    return "md:col-span-11";
                  case 12:
                    return "md:col-span-12";
                  default:
                    return "md:col-span-12";
                }
              };
              return /* @__PURE__ */ jsx(
                "div",
                {
                  className: getColumnSpanClass(field.display.columnWidth),
                  "data-cy": sel("entities.form.field", { slug: entityConfig.slug, name: field.name }),
                  children: /* @__PURE__ */ jsx(
                    EntityFieldRenderer,
                    {
                      field,
                      value: formData[field.name],
                      onChange: (value) => handleFieldChange(field.name, value),
                      mode: "form",
                      error: allErrors[field.name],
                      disabled: isSubmitting || field.api.readOnly || disabledFields.includes(field.name),
                      required: field.required,
                      testId: testIds.field(field.name),
                      context: {
                        entityType: entityConfig.slug,
                        formData,
                        teamId
                      }
                    }
                  )
                },
                field.name
              );
            }) }) }) })
          ),
          /* @__PURE__ */ jsx("div", { className: "flex flex-col sm:flex-row gap-3 justify-end pt-6", children: /* @__PURE__ */ jsxs(
            Button,
            {
              type: "submit",
              disabled: isSubmitting || isLoading,
              "data-testid": testIds.submit,
              "data-cy": sel("entities.form.submitButton", { slug: entityConfig.slug }),
              children: [
                isSubmitting || isLoading ? /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }) : /* @__PURE__ */ jsx(Save, { className: "mr-2 h-4 w-4" }),
                mode === "create" ? "Create" : "Save Changes"
              ]
            }
          ) })
        ]
      }
    )
  ] });
}
export {
  EntityForm
};
