"use client";

import { useQuery } from "@tanstack/react-query";
import { PageHeader } from "@/components/shared/page-header";
import { ErrorState } from "@/components/shared/states";
import { Alert } from "@/components/ui/alert";
import { Skeleton } from "@/components/ui/skeleton";
import { AllowedIpsCard } from "@/features/portal/integration/allowed-ips-card";
import { WrappingCard } from "@/features/portal/integration/wrapping-card";
import { EndpointCard } from "@/features/portal/integration/endpoint-card";
import { SecretsCard } from "@/features/portal/integration/secrets-card";
import { TokenCard } from "@/features/portal/integration/token-card";
import { WebhookCard } from "@/features/portal/integration/webhook-card";
import { useT } from "@/i18n";
import { friendlyErrorMessage } from "@/lib/errors";
import { queryKeys } from "@/lib/query-keys";
import { getPortalSettings } from "@/services/portal";

/**
 * Everything a store sets up to connect its servers, in the order they do it: where our API is,
 * the token and keys that prove who is calling, then where we answer and who may call.
 *
 * Owner only — the shell and the API both enforce it. A store under review reaches this page on
 * purpose, so it can finish its own setup while the review runs.
 */
export default function PortalIntegrationPage() {
  const t = useT();

  const { data, isLoading, isError, error, refetch } = useQuery({
    queryKey: queryKeys.portal.settings,
    queryFn: async () => (await getPortalSettings()).Model,
  });

  const store = data ?? null;

  return (
    <div className="mx-auto max-w-3xl">
      <PageHeader title={t("portal.integration.title")} subtitle={t("portal.integration.subtitle")} />

      {isLoading ? (
        <div className="space-y-4" aria-busy>
          <Skeleton className="h-36 w-full" />
          <Skeleton className="h-36 w-full" />
          <Skeleton className="h-36 w-full" />
        </div>
      ) : isError || !store ? (
        <ErrorState
          message={isError ? friendlyErrorMessage(error, t) : t("portal.integration.loadFailed")}
          onRetry={() => void refetch()}
        />
      ) : (
        <div className="space-y-4">
          {store.status !== "approved" ? (
            <Alert variant="info" title={t("portal.integration.pendingNote")} />
          ) : null}
          <EndpointCard />
          <TokenCard store={store} />
          <SecretsCard store={store} />
          <WebhookCard store={store} />
          <AllowedIpsCard store={store} />
          <WrappingCard store={store} />
        </div>
      )}
    </div>
  );
}
