// @design-system: checkout/CheckoutComplete
/**
 * CheckoutComplete - polls /api/checkout/finalize after Stripe redirect.
 *
 * Polls every 2s up to ~30s. Shows Spinner while pending,
 * success InlineNotice on ok, ErrorState on failure.
 *
 * @example
 * <CheckoutComplete
 *   purchaseId="uuid"
 *   providerPaymentId="pi_..."
 *   initialStatus="succeeded"
 * />
 */

'use client';

import { useEffect, useRef, useState } from 'react';
import { useT } from '@/lib/i18n/react';
import { Spinner } from '@/components/ui/feedback/Spinner';
import { InlineNotice } from '@/components/ui/feedback/InlineNotice';
import { ErrorState } from '@/components/ui/feedback/ErrorState';
import { Button } from '@/components/ui/primitives/Button';
import { getCsrfToken } from '@/lib/csrf';
import { captureCaught } from '@/lib/observability';
import { HydratedIsland } from '@/components/HydratedIsland';
import type { Locale } from '@/lib/i18n';

// ─── Types ──────────────────────────────────────────────────────────────────

export interface CheckoutCompleteProps {
  locale?: Locale;
  purchaseId: string;
  providerPaymentId: string;
  /** Stripe redirect_status query param value (e.g. "succeeded"). */
  initialStatus?: string | null;
  /** Design-system gallery mode: render static success, never poll or redirect. */
  demo?: boolean;
}

type PollState = 'polling' | 'success' | 'error';

// ─── Component ───────────────────────────────────────────────────────────────

const MAX_POLLS = 15; // 15 × 2000ms = 30s
const POLL_INTERVAL_MS = 2000;

function CheckoutCompleteInner({ purchaseId, providerPaymentId, demo }: CheckoutCompleteProps) {
  const t = useT('checkout');
  const [state, setState] = useState<PollState>(demo ? 'success' : 'polling');
  const [errDetail, setErrDetail] = useState<string | null>(null);
  const pollCount = useRef(0);
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    if (demo) return;
    let cancelled = false;

    async function poll() {
      if (cancelled) return;
      if (pollCount.current >= MAX_POLLS) {
        setState('error');
        setErrDetail(t('complete_timeout'));
        return;
      }
      pollCount.current += 1;

      try {
        const res = await fetch('/api/checkout/finalize', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'x-csrf-token': getCsrfToken(),
          },
          body: JSON.stringify({ providerPaymentId }),
        });
        const data = (await res.json()) as { ok?: boolean; code?: string; message?: string };

        if (cancelled) return;

        if (data.ok) {
          setState('success');
          // Redirect to confirmation page
          window.location.href = `/purchases/${purchaseId}/confirmation`;
          return;
        }

        // STILL_PROCESSING → keep polling
        if (data.code === 'STILL_PROCESSING' || res.status === 202) {
          timerRef.current = setTimeout(poll, POLL_INTERVAL_MS);
          return;
        }

        // Any other non-ok response → error
        setState('error');
        setErrDetail(data.message ?? t('payment_failed'));
      } catch (err) {
        if (cancelled) return;
        captureCaught(err, {
          scope: 'ui.checkout.CheckoutComplete',
          severity: 'warning',
          extra: { purchaseId, providerPaymentId },
        });
        setState('error');
        setErrDetail(t('payment_failed'));
      }
    }

    void poll();

    return () => {
      cancelled = true;
      if (timerRef.current) clearTimeout(timerRef.current);
    };
  }, [purchaseId, providerPaymentId, demo, t]);

  if (state === 'polling') {
    return (
      <div
        role="status"
        aria-live="polite"
        className="flex min-h-[var(--spacing-40)] flex-col items-center justify-center gap-4"
      >
        <Spinner variant="dots" size="md" label={t('complete_pending')} />
        <p className="text-text-secondary text-sm">{t('complete_pending')}</p>
      </div>
    );
  }

  if (state === 'success') {
    return (
      <div className="flex flex-col gap-4 p-6">
        <InlineNotice
          tone="success"
          title={t('complete_success_title')}
          description={t('complete_success_body')}
        />
        <Button variant="secondary" asChild>
          <a href={`/purchases/${purchaseId}`}>{t('view_purchase')}</a>
        </Button>
      </div>
    );
  }

  // error state
  return (
    <ErrorState
      title={t('complete_error_title')}
      description={errDetail ?? t('payment_failed')}
      action={
        <Button variant="ghost" onClick={() => window.location.reload()}>
          {t('try_again')}
        </Button>
      }
    />
  );
}

export function CheckoutComplete({ locale, ...props }: CheckoutCompleteProps) {
  return (
    <HydratedIsland locale={locale}>
      <CheckoutCompleteInner {...props} />
    </HydratedIsland>
  );
}
