"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useState, useEffect } from "react";
import Link from "next/link";
import { Button } from "../../ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../../ui/card";
import { Badge } from "../../ui/badge";
import { Separator } from "../../ui/separator";
import { Skeleton } from "../../ui/skeleton";
import { Alert, AlertDescription } from "../../ui/alert";
import { ArrowLeft, CalendarDays, Clock } from "lucide-react";
import { entityApi } from "../../../lib/api/entities";
import { getAllEntityConfigs } from "../../../lib/entities/registry.client";
import { SYSTEM_TIMESTAMP_FIELDS } from "../../../lib/entities/system-fields";
function PublicEntityDetail({ entityType, entitySlug, id, className }) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [entityConfig, setEntityConfig] = useState(null);
  useEffect(() => {
    try {
      const configs = getAllEntityConfigs();
      const config = configs.find((c) => c.slug === entitySlug);
      setEntityConfig(config || null);
    } catch (err) {
      console.error("Failed to load entity config:", err);
    }
  }, [entitySlug]);
  useEffect(() => {
    const loadData = async () => {
      try {
        setLoading(true);
        setError(null);
        const result = await entityApi.get(entityType, id);
        setData(result);
      } catch (err) {
        console.error("Error loading public entity:", err);
        setError(err instanceof Error ? err.message : "Failed to load data");
      } finally {
        setLoading(false);
      }
    };
    loadData();
  }, [entityType, id]);
  const titleField = entityConfig == null ? void 0 : entityConfig.fields.find(
    (field) => ["title", "name"].includes(field.name) && field.display.showInDetail
  );
  const descriptionField = entityConfig == null ? void 0 : entityConfig.fields.find(
    (field) => ["description", "summary", "content", "excerpt"].includes(field.name) && field.display.showInDetail
  );
  const detailFields = (entityConfig == null ? void 0 : entityConfig.fields.filter(
    (field) => field.display.showInDetail && !["id", "userId"].includes(field.name) && field.name !== (titleField == null ? void 0 : titleField.name) && field.name !== (descriptionField == null ? void 0 : descriptionField.name)
  )) || [];
  const metadataFields = SYSTEM_TIMESTAMP_FIELDS;
  const contentFields = detailFields.filter(
    (field) => !["createdAt", "updatedAt"].includes(field.name)
  );
  const formatDate = (dateString) => {
    try {
      return new Date(dateString).toLocaleDateString("en-US", {
        year: "numeric",
        month: "long",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit"
      });
    } catch {
      return dateString;
    }
  };
  const formatFieldValue = (field, value) => {
    var _a;
    if (value === null || value === void 0) return "Not specified";
    switch (field.type) {
      case "date":
      case "datetime":
        return formatDate(value);
      case "boolean":
        return value ? "Yes" : "No";
      case "number":
        return typeof value === "number" ? value.toLocaleString() : String(value);
      case "email":
        return /* @__PURE__ */ jsx("a", { href: `mailto:${value}`, className: "text-primary hover:underline", children: value });
      case "url":
        return /* @__PURE__ */ jsx("a", { href: value, target: "_blank", rel: "noopener noreferrer", className: "text-primary hover:underline", children: value });
      case "select":
        const option = (_a = field.options) == null ? void 0 : _a.find((opt) => opt.value === value);
        return (option == null ? void 0 : option.label) || String(value);
      case "text":
        return /* @__PURE__ */ jsx("div", { className: "whitespace-pre-wrap", children: String(value) });
      default:
        return String(value);
    }
  };
  if (error) {
    return /* @__PURE__ */ jsx(Alert, { variant: "destructive", children: /* @__PURE__ */ jsx(AlertDescription, { children: error }) });
  }
  if (loading || !entityConfig) {
    return /* @__PURE__ */ jsxs("div", { className: `space-y-6 ${className}`, children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4", children: [
        /* @__PURE__ */ jsx(Skeleton, { className: "h-10 w-20" }),
        /* @__PURE__ */ jsx(Skeleton, { className: "h-8 w-32" })
      ] }),
      /* @__PURE__ */ jsxs(Card, { children: [
        /* @__PURE__ */ jsxs(CardHeader, { children: [
          /* @__PURE__ */ jsx(Skeleton, { className: "h-8 w-3/4" }),
          /* @__PURE__ */ jsx(Skeleton, { className: "h-4 w-full" }),
          /* @__PURE__ */ jsx(Skeleton, { className: "h-4 w-2/3" })
        ] }),
        /* @__PURE__ */ jsx(CardContent, { children: /* @__PURE__ */ jsx("div", { className: "space-y-4", children: Array.from({ length: 6 }).map((_, i) => /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
          /* @__PURE__ */ jsx(Skeleton, { className: "h-4 w-24" }),
          /* @__PURE__ */ jsx(Skeleton, { className: "h-4 w-32" })
        ] }, i)) }) })
      ] })
    ] });
  }
  if (!data) {
    return /* @__PURE__ */ jsx(Alert, { variant: "destructive", children: /* @__PURE__ */ jsxs(AlertDescription, { children: [
      (entityConfig == null ? void 0 : entityConfig.names.singular) || "Entity",
      " not found"
    ] }) });
  }
  const title = titleField ? data[titleField.name] : `${(entityConfig == null ? void 0 : entityConfig.names.singular) || "Entity"} ${id}`;
  const description = descriptionField ? data[descriptionField.name] : void 0;
  return /* @__PURE__ */ jsxs("div", { className: `space-y-6 ${className}`, children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4", children: [
      /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", asChild: true, children: /* @__PURE__ */ jsxs(Link, { href: `/${(entityConfig == null ? void 0 : entityConfig.slug) || ""}`, children: [
        /* @__PURE__ */ jsx(ArrowLeft, { className: "h-4 w-4 mr-2" }),
        "Back to ",
        (entityConfig == null ? void 0 : entityConfig.names.plural) || "List"
      ] }) }),
      /* @__PURE__ */ jsx(Badge, { variant: "outline", children: (entityConfig == null ? void 0 : entityConfig.names.singular) || "Entity" })
    ] }),
    /* @__PURE__ */ jsxs(Card, { children: [
      /* @__PURE__ */ jsxs(CardHeader, { children: [
        /* @__PURE__ */ jsx(CardTitle, { className: "text-2xl font-bold", children: title }),
        description && /* @__PURE__ */ jsx(CardDescription, { className: "text-base leading-relaxed", children: description })
      ] }),
      /* @__PURE__ */ jsxs(CardContent, { className: "space-y-6", children: [
        contentFields.length > 0 && /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
          /* @__PURE__ */ jsx("h3", { className: "text-lg font-semibold", children: "Details" }),
          /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-4", children: contentFields.map((field) => /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
            /* @__PURE__ */ jsx("label", { className: "text-sm font-medium text-muted-foreground", children: field.display.label }),
            /* @__PURE__ */ jsx("div", { className: "text-sm text-foreground", children: formatFieldValue(field, data[field.name]) })
          ] }, field.name)) })
        ] }),
        metadataFields.length > 0 && /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsx(Separator, {}),
          /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm text-muted-foreground", children: metadataFields.map((field) => {
            const Icon = field.name === "createdAt" ? CalendarDays : Clock;
            return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsx(Icon, { className: "h-4 w-4" }),
              /* @__PURE__ */ jsxs("span", { children: [
                field.display.label,
                ": ",
                formatFieldValue(field, data[field.name])
              ] })
            ] }, field.name);
          }) })
        ] })
      ] })
    ] }),
    /* @__PURE__ */ jsx("div", { className: "flex justify-center", children: /* @__PURE__ */ jsx(Button, { variant: "outline", asChild: true, children: /* @__PURE__ */ jsxs(Link, { href: `/${(entityConfig == null ? void 0 : entityConfig.slug) || ""}`, children: [
      "View More ",
      (entityConfig == null ? void 0 : entityConfig.names.plural) || "Items"
    ] }) }) })
  ] });
}
export {
  PublicEntityDetail
};
