"use client";

import { useQuery } from "@tanstack/react-query";
import Link from "next/link";
import { useTenantId } from "@/hooks/useTenantId";
import { experienceApi } from "@/modules/experience/services/experience-api";
import { ExperiencePageLoader, ExperiencePageError } from "@/modules/experience/pages/shared";
import { ExperienceBreadcrumbs } from "@/modules/experience/components/ExperienceBreadcrumbs";
import { PageHeader, Card, CardContent, Badge, Button } from "@/components/ds";
import { ExperienceTablePage } from "@/modules/experience/design-system";

export const PublishTargetsPage = function ExperiencePublishTargets() {
  const { tenantId } = useTenantId();

  const q = useQuery({
    queryKey: ["experience", tenantId, "publish-targets"],
    queryFn: async () => {
      const [sites, pages] = await Promise.all([
        experienceApi.sites.list(tenantId!),
        experienceApi.pages.list(tenantId!),
      ]);
      return [
        ...sites.map((s) => ({
          id: s.id,
          kind: "site",
          name: s.name ?? s.code,
          publish_status: s.publish_status,
          publish_id_provisional: s.id,
        })),
        ...pages.map((p) => ({
          id: p.id,
          kind: "page",
          name: p.title ?? p.slug,
          publish_status: p.publish_status,
          publish_id_provisional: p.id,
        })),
      ];
    },
    enabled: !!tenantId,
  });

  if (!tenantId || q.isLoading) return <ExperiencePageLoader />;
  if (q.error) return <ExperiencePageError error={q.error} onRetry={() => q.refetch()} />;

  const rows = (q.data ?? []) as Record<string, unknown>[];

  return (
    <div className="space-y-4">
      <ExperienceBreadcrumbs current="اهداف انتشار" />
      <PageHeader
        title="اهداف انتشار"
        description="سطح‌های قابل انتشار — publish_id موقت = شناسه منبع تا رجیstry رسمی (FE-11.6+)."
      />
      <ExperienceTablePage
        title=""
        columns={[
          { key: "kind", header: "نوع" },
          { key: "name", header: "نام" },
          { key: "publish_status", header: "وضعیت" },
          {
            key: "publish_id_provisional",
            header: "publish_id (موقت)",
            render: (row) => (
              <Badge tone="warning">{String(row.publish_id_provisional)}</Badge>
            ),
          },
          {
            key: "preview",
            header: "پیش‌نمایش",
            render: (row) => (
              <Link href={`/experience/preview/${row.kind}/${row.id}`}>
                <Button variant="outline" size="sm">مشاهده</Button>
              </Link>
            ),
          },
        ]}
        rows={rows}
      />
    </div>
  );
};

export default PublishTargetsPage;
