"use client";

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
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, FormField, Select } from "@/components/ds";

export const EmbedPreviewPage = function ExperienceEmbedPreview() {
  const { tenantId } = useTenantId();
  const [instanceId, setInstanceId] = useState("");

  const defsQ = useQuery({
    queryKey: ["experience", tenantId, "widget-defs"],
    queryFn: () => experienceApi.widgetDefinitions.list(tenantId!),
    enabled: !!tenantId,
  });

  const instancesQ = useQuery({
    queryKey: ["experience", tenantId, "widget-instances"],
    queryFn: () => experienceApi.widgetInstances.list(tenantId!),
    enabled: !!tenantId,
  });

  const selected = instancesQ.data?.find((i) => String(i.id) === instanceId);
  const publishId = selected ? String(selected.id) : "—";
  const embedSnippet = selected
    ? `<script src="https://cdn.torbatyar.ir/embed.js" data-publish-id="${publishId}" async></script>`
    : "یک نمونه ویجت انتخاب کنید";

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

  return (
    <div className="space-y-6">
      <ExperienceBreadcrumbs current="پیش‌نمایش Embed" />
      <PageHeader title="پیش‌نمایش Embed" description="snippet embed با publish_id موقت (شناسه نمونه ویجت)." />
      <Card>
        <CardContent className="space-y-4 p-4">
          <FormField label="نمونه ویجت">
            <Select value={instanceId} onChange={(e) => setInstanceId(e.target.value)}>
              <option value="">انتخاب…</option>
              {(instancesQ.data ?? []).map((i) => (
                <option key={String(i.id)} value={String(i.id)}>
                  {String(i.embed_ref ?? i.id)}
                </option>
              ))}
            </Select>
          </FormField>
          <Badge tone="warning">publish_id موقت: {publishId}</Badge>
          <pre className="overflow-x-auto rounded-lg bg-[var(--surface-muted)] p-4 text-xs">{embedSnippet}</pre>
          <p className="text-xs text-[var(--muted)]">
            تعاریف ویجت: {defsQ.data?.length ?? 0} — پس از FE-11.6+ publish_id رسمی از registry خواهد آمد.
          </p>
        </CardContent>
      </Card>
    </div>
  );
};

export default EmbedPreviewPage;
