"use client";

import { useParams } from "next/navigation";
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 { PageHeader, Card, CardContent, Badge, Button } from "@/components/ds";

export const PublicPreviewPage = function ExperiencePublicPreview() {
  const params = useParams();
  const type = String(params.type);
  const id = String(params.id);
  const { tenantId } = useTenantId();

  const resourceQ = useQuery({
    queryKey: ["experience", tenantId, "preview", type, id],
    queryFn: async () => {
      if (type === "page") return experienceApi.pages.get(tenantId!, id);
      if (type === "site") return experienceApi.sites.get(tenantId!, id);
      if (type === "form") return experienceApi.forms.get(tenantId!, id);
      throw new Error("نوع نامعتبر");
    },
    enabled: !!tenantId && !!id,
  });

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

  const r = resourceQ.data!;
  const title = String(r.title ?? r.name ?? r.code ?? id);

  return (
    <div className="min-h-screen bg-[var(--canvas)]">
      <header className="border-b border-[var(--border)] bg-[var(--surface)] px-4 py-3">
        <div className="mx-auto flex max-w-4xl items-center justify-between">
          <Badge tone="info">پیش‌نمایش عمومی</Badge>
          <Badge>publish_id موقت: {id}</Badge>
        </div>
      </header>
      <main className="mx-auto max-w-4xl p-6">
        <PageHeader title={title} description={`نوع: ${type}`} />
        <Card>
          <CardContent className="space-y-4 p-6">
            <pre className="overflow-x-auto rounded-lg bg-[var(--surface-muted)] p-4 text-xs">
              {JSON.stringify(r, null, 2)}
            </pre>
            <Link href={`/experience/${type}s`}>
              <Button variant="outline">بازگشت به پنل</Button>
            </Link>
          </CardContent>
        </Card>
      </main>
    </div>
  );
};

export default PublicPreviewPage;
