"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useState, useEffect, useMemo } from "react";
import { PublicEntityCard } from "./PublicEntityCard";
import { Button } from "../../ui/button";
import { Input } from "../../ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../ui/select";
import { Skeleton } from "../../ui/skeleton";
import { Alert, AlertDescription } from "../../ui/alert";
import { Search, SortAsc, SortDesc, Grid, List } 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 PublicEntityGrid({ entityType, entitySlug, searchParams, className }) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [searchTerm, setSearchTerm] = useState(searchParams.search || "");
  const [sortField, setSortField] = useState(searchParams.sort || "createdAt");
  const [sortDirection, setSortDirection] = useState(
    searchParams.order === "asc" ? "asc" : "desc"
  );
  const [currentPage, setCurrentPage] = useState(parseInt(searchParams.page) || 1);
  const [viewMode, setViewMode] = useState("grid");
  const [entityConfig, setEntityConfig] = useState(null);
  const pageSize = 12;
  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]);
  const sortableFields = useMemo(() => {
    const configFields = (entityConfig == null ? void 0 : entityConfig.fields.filter(
      (field) => {
        var _a;
        return ((_a = field.api) == null ? void 0 : _a.sortable) && field.display.showInList;
      }
    )) || [];
    const implicitFields = SYSTEM_TIMESTAMP_FIELDS.filter(
      (field) => !configFields.some((f) => f.name === field.name)
    );
    return [...configFields, ...implicitFields];
  }, [entityConfig]);
  useEffect(() => {
    const loadData = async () => {
      try {
        setLoading(true);
        setError(null);
        const params = {
          page: currentPage,
          limit: pageSize
        };
        if (searchTerm.trim()) {
          params.search = searchTerm.trim();
        }
        if (sortField) {
          params.sort = sortField;
          params.order = sortDirection;
        }
        const result = await entityApi.list(entityType, params);
        setData(result);
      } catch (err) {
        console.error("Error loading public entities:", err);
        setError(err instanceof Error ? err.message : "Failed to load data");
      } finally {
        setLoading(false);
      }
    };
    loadData();
  }, [entityType, currentPage, searchTerm, sortField, sortDirection]);
  const handleSearch = (value) => {
    setSearchTerm(value);
    setCurrentPage(1);
  };
  const handlePageChange = (page) => {
    setCurrentPage(page);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };
  if (error) {
    return /* @__PURE__ */ jsx(Alert, { variant: "destructive", children: /* @__PURE__ */ jsx(AlertDescription, { children: error }) });
  }
  return /* @__PURE__ */ jsxs("div", { className: `space-y-6 ${className}`, children: [
    /* @__PURE__ */ jsxs("div", { className: "flex flex-col sm:flex-row gap-4 items-center justify-between", children: [
      /* @__PURE__ */ jsxs("div", { className: "relative flex-1 max-w-md", children: [
        /* @__PURE__ */ jsx(Search, { className: "absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" }),
        /* @__PURE__ */ jsx(
          Input,
          {
            placeholder: entityConfig ? `Search ${entityConfig.names.plural.toLowerCase()}...` : "Search...",
            value: searchTerm,
            onChange: (e) => handleSearch(e.target.value),
            className: "pl-10"
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
        sortableFields.length > 0 && /* @__PURE__ */ jsxs(Select, { value: sortField, onValueChange: setSortField, children: [
          /* @__PURE__ */ jsx(SelectTrigger, { className: "w-[180px]", children: /* @__PURE__ */ jsx(SelectValue, { placeholder: "Sort by..." }) }),
          /* @__PURE__ */ jsx(SelectContent, { children: sortableFields.map((field) => /* @__PURE__ */ jsx(SelectItem, { value: field.name, children: field.display.label }, field.name)) })
        ] }),
        /* @__PURE__ */ jsx(
          Button,
          {
            variant: "outline",
            size: "sm",
            onClick: () => setSortDirection(sortDirection === "asc" ? "desc" : "asc"),
            children: sortDirection === "asc" ? /* @__PURE__ */ jsx(SortAsc, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(SortDesc, { className: "h-4 w-4" })
          }
        ),
        /* @__PURE__ */ jsxs("div", { className: "flex border rounded-md", children: [
          /* @__PURE__ */ jsx(
            Button,
            {
              variant: viewMode === "grid" ? "default" : "ghost",
              size: "sm",
              onClick: () => setViewMode("grid"),
              className: "rounded-r-none",
              children: /* @__PURE__ */ jsx(Grid, { className: "h-4 w-4" })
            }
          ),
          /* @__PURE__ */ jsx(
            Button,
            {
              variant: viewMode === "list" ? "default" : "ghost",
              size: "sm",
              onClick: () => setViewMode("list"),
              className: "rounded-l-none",
              children: /* @__PURE__ */ jsx(List, { className: "h-4 w-4" })
            }
          )
        ] })
      ] })
    ] }),
    data && data.info && entityConfig && /* @__PURE__ */ jsxs("div", { className: "text-sm text-muted-foreground", children: [
      "Showing ",
      data.data.length,
      " of ",
      data.info.total,
      " ",
      entityConfig.names.plural.toLowerCase()
    ] }),
    loading && /* @__PURE__ */ jsx("div", { className: `grid gap-6 ${viewMode === "grid" ? "grid-cols-1 md:grid-cols-2 lg:grid-cols-3" : "grid-cols-1"}`, children: Array.from({ length: pageSize }).map((_, i) => /* @__PURE__ */ jsx(Skeleton, { className: "h-48 w-full" }, i)) }),
    data && data.data.length > 0 && /* @__PURE__ */ jsx("div", { className: `grid gap-6 ${viewMode === "grid" ? "grid-cols-1 md:grid-cols-2 lg:grid-cols-3" : "grid-cols-1"}`, children: data.data.map((item) => /* @__PURE__ */ jsx(
      PublicEntityCard,
      {
        entityConfig,
        entitySlug,
        data: item,
        className: viewMode === "list" ? "flex-row" : ""
      },
      `${item.id}-${entityConfig ? "loaded" : "loading"}`
    )) }),
    data && data.data.length === 0 && entityConfig && /* @__PURE__ */ jsxs("div", { className: "text-center py-12", children: [
      /* @__PURE__ */ jsxs("div", { className: "text-muted-foreground text-lg mb-2", children: [
        "No ",
        entityConfig.names.plural.toLowerCase(),
        " found"
      ] }),
      searchTerm && /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground", children: "Try adjusting your search terms" })
    ] }),
    data && data.info && data.info.totalPages > 1 && /* @__PURE__ */ jsxs("div", { className: "flex justify-center items-center gap-2", children: [
      /* @__PURE__ */ jsx(
        Button,
        {
          variant: "outline",
          disabled: !data.info.hasPrevPage,
          onClick: () => handlePageChange(currentPage - 1),
          children: "Previous"
        }
      ),
      /* @__PURE__ */ jsx("div", { className: "flex items-center gap-1", children: Array.from({ length: Math.min(5, data.info.totalPages) }, (_, i) => {
        const page = currentPage <= 3 ? i + 1 : currentPage - 2 + i;
        if (page > data.info.totalPages) return null;
        return /* @__PURE__ */ jsx(
          Button,
          {
            variant: page === currentPage ? "default" : "outline",
            size: "sm",
            onClick: () => handlePageChange(page),
            children: page
          },
          page
        );
      }) }),
      /* @__PURE__ */ jsx(
        Button,
        {
          variant: "outline",
          disabled: !data.info.hasNextPage,
          onClick: () => handlePageChange(currentPage + 1),
          children: "Next"
        }
      )
    ] })
  ] });
}
export {
  PublicEntityGrid
};
