"use client";
import { jsx, jsxs } from 'react/jsx-runtime';
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { ChevronDown, ChevronRight, ExternalLink, Trash2, Plus } from 'lucide-react';
import { Button } from '../../../../../../ui/src/components/button.mjs';
import { Card, CardHeader, CardTitle, CardContent } from '../../../../../../ui/src/components/card.mjs';
import { createApiClient } from '@btst/stack/plugins/client';
import { usePluginOverrides, useBasePath } from '@btst/stack/context';
import { AlertDialog, AlertDialogContent, AlertDialogHeader, AlertDialogTitle, AlertDialogDescription, AlertDialogFooter, AlertDialogCancel, AlertDialogAction } from '../../../../../../ui/src/components/alert-dialog.mjs';
import { useDeleteContent } from '../hooks/cms-hooks.mjs';

function InverseRelationsPanel({
  contentTypeSlug,
  itemId
}) {
  const { apiBaseURL, apiBasePath, headers, navigate, Link } = usePluginOverrides("cms");
  const basePath = useBasePath();
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const { data: inverseRelationsData, isLoading } = useQuery({
    queryKey: ["cmsInverseRelations", contentTypeSlug, itemId],
    queryFn: async () => {
      const response = await client("/content-types/:slug/inverse-relations", {
        method: "GET",
        params: { slug: contentTypeSlug },
        query: { itemId },
        headers
      });
      return response.data?.inverseRelations ?? [];
    },
    staleTime: 1e3 * 60 * 5
  });
  if (isLoading) {
    return /* @__PURE__ */ jsx(Card, { className: "animate-pulse", children: /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx("div", { className: "h-5 w-32 bg-muted rounded" }) }) });
  }
  const inverseRelations = inverseRelationsData ?? [];
  if (inverseRelations.length === 0) {
    return null;
  }
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsx("h3", { className: "text-lg font-semibold", children: "Related Items" }),
    inverseRelations.map((relation) => /* @__PURE__ */ jsx(
      InverseRelationSection,
      {
        relation,
        contentTypeSlug,
        itemId,
        basePath,
        navigate,
        Link,
        client,
        headers
      },
      `${relation.sourceType}-${relation.fieldName}`
    ))
  ] });
}
function InverseRelationSection({
  relation,
  contentTypeSlug,
  itemId,
  basePath,
  navigate,
  Link,
  client,
  headers
}) {
  const [isExpanded, setIsExpanded] = useState(true);
  const [deleteItemId, setDeleteItemId] = useState(null);
  const [deleteError, setDeleteError] = useState(null);
  const deleteContent = useDeleteContent(relation.sourceType);
  const { data: itemsData, refetch } = useQuery({
    queryKey: [
      "cmsInverseRelationItems",
      contentTypeSlug,
      relation.sourceType,
      itemId,
      relation.fieldName
    ],
    queryFn: async () => {
      const response = await client(
        "/content-types/:slug/inverse-relations/:sourceType",
        {
          method: "GET",
          params: { slug: contentTypeSlug, sourceType: relation.sourceType },
          query: { itemId, fieldName: relation.fieldName },
          headers
        }
      );
      return response.data ?? { items: [], total: 0 };
    },
    staleTime: 1e3 * 60 * 5,
    enabled: isExpanded
  });
  const items = itemsData?.items ?? [];
  const total = itemsData?.total ?? relation.count;
  const handleDelete = async () => {
    if (deleteItemId) {
      setDeleteError(null);
      try {
        await deleteContent.mutateAsync(deleteItemId);
        setDeleteItemId(null);
        refetch();
      } catch (error) {
        const message = error instanceof Error ? error.message : "Failed to delete item. Please try again.";
        setDeleteError(message);
      }
    }
  };
  const handleAddNew = () => {
    const createUrl = `${basePath}/cms/${relation.sourceType}/new?prefill_${relation.fieldName}=${itemId}`;
    navigate(createUrl);
  };
  const LinkComponent = Link ?? "a";
  return /* @__PURE__ */ jsxs(Card, { children: [
    /* @__PURE__ */ jsx(CardHeader, { className: "py-3", children: /* @__PURE__ */ jsx(
      "button",
      {
        type: "button",
        onClick: () => setIsExpanded(!isExpanded),
        className: "flex items-center justify-between w-full text-left",
        children: /* @__PURE__ */ jsxs(CardTitle, { className: "text-base flex items-center gap-2", children: [
          isExpanded ? /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(ChevronRight, { className: "h-4 w-4" }),
          relation.sourceTypeName,
          " (",
          total,
          ")"
        ] })
      }
    ) }),
    isExpanded && /* @__PURE__ */ jsxs(CardContent, { className: "pt-0", children: [
      items.length === 0 ? /* @__PURE__ */ jsxs("p", { className: "text-sm text-muted-foreground py-2", children: [
        "No ",
        relation.sourceTypeName.toLowerCase(),
        " items yet."
      ] }) : /* @__PURE__ */ jsx("ul", { className: "space-y-2", children: items.map((item) => {
        const displayValue = getDisplayValue(item);
        const editUrl = `${basePath}/cms/${relation.sourceType}/${item.id}`;
        return /* @__PURE__ */ jsxs(
          "li",
          {
            className: "flex items-center justify-between py-2 px-3 rounded-md bg-muted/50 hover:bg-muted transition-colors",
            children: [
              /* @__PURE__ */ jsxs(
                LinkComponent,
                {
                  href: editUrl,
                  className: "flex-1 text-sm hover:underline flex items-center gap-2",
                  children: [
                    /* @__PURE__ */ jsx("span", { className: "truncate", children: displayValue }),
                    /* @__PURE__ */ jsx(ExternalLink, { className: "h-3 w-3 opacity-50" })
                  ]
                }
              ),
              /* @__PURE__ */ jsx(
                Button,
                {
                  variant: "ghost",
                  size: "icon",
                  className: "h-7 w-7 text-muted-foreground hover:text-destructive",
                  onClick: () => setDeleteItemId(item.id),
                  children: /* @__PURE__ */ jsx(Trash2, { className: "h-3.5 w-3.5" })
                }
              )
            ]
          },
          item.id
        );
      }) }),
      /* @__PURE__ */ jsx("div", { className: "mt-3 pt-3 border-t", children: /* @__PURE__ */ jsxs(
        Button,
        {
          variant: "outline",
          size: "sm",
          onClick: handleAddNew,
          className: "w-full",
          children: [
            /* @__PURE__ */ jsx(Plus, { className: "h-4 w-4 mr-2" }),
            "Add ",
            relation.sourceTypeName
          ]
        }
      ) })
    ] }),
    /* @__PURE__ */ jsx(
      AlertDialog,
      {
        open: !!deleteItemId,
        onOpenChange: (open) => {
          if (!open) {
            setDeleteItemId(null);
            setDeleteError(null);
          }
        },
        children: /* @__PURE__ */ jsxs(AlertDialogContent, { children: [
          /* @__PURE__ */ jsxs(AlertDialogHeader, { children: [
            /* @__PURE__ */ jsxs(AlertDialogTitle, { children: [
              "Delete ",
              relation.sourceTypeName,
              "?"
            ] }),
            /* @__PURE__ */ jsxs(AlertDialogDescription, { children: [
              "This action cannot be undone. This will permanently delete this",
              " ",
              relation.sourceTypeName.toLowerCase(),
              "."
            ] })
          ] }),
          deleteError && /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: deleteError }),
          /* @__PURE__ */ jsxs(AlertDialogFooter, { children: [
            /* @__PURE__ */ jsx(AlertDialogCancel, { children: "Cancel" }),
            /* @__PURE__ */ jsx(
              AlertDialogAction,
              {
                onClick: handleDelete,
                className: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
                children: "Delete"
              }
            )
          ] })
        ] })
      }
    )
  ] });
}
function getDisplayValue(item) {
  const data = item.parsedData;
  const displayFields = ["name", "title", "label", "content", "author", "slug"];
  for (const field of displayFields) {
    if (typeof data[field] === "string" && data[field]) {
      const value = data[field];
      return value.length > 50 ? `${value.slice(0, 50)}...` : value;
    }
  }
  return item.slug;
}

export { InverseRelationsPanel };
