'use client';

import { useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthStore } from '@/store/authStore';

/**
 * Payment success page — Creem redirect callback.
 *
 * After payment Creem redirects to this page with query params:
 *   checkout_id, order_id, customer_id, subscription_id, product_id,
 *   request_id (optional), signature
 *
 * We forward all params to the backend, which verifies the signature
 * and activates the user's plan.
 */
export default function PaymentSuccessPage() {
  const router = useRouter();
  const { verifyCheckout, isAuthenticated, hasHydrated } = useAuthStore();
  const verified = useRef(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (verified.current) return;
    if (!hasHydrated) return;

    const params = new URLSearchParams(window.location.search);
    const checkoutId = params.get('checkout_id') ?? params.get('checkoutId');

    if (!checkoutId) {
      router.replace('/');
      return;
    }

    if (!isAuthenticated) {
      sessionStorage.setItem('pendingCheckoutId', checkoutId);
      router.replace(`/signin?redirect=/payment/success?${params.toString()}`);
      return;
    }

    verified.current = true;

    // Collect all Creem redirect params and forward the raw query string
    // so the backend can reconstruct the canonical signature in URL order.
    const redirectParams = {
      checkoutId,
      orderId:        params.get('order_id')        ?? undefined,
      customerId:     params.get('customer_id')     ?? undefined,
      subscriptionId: params.get('subscription_id') ?? undefined,
      productId:      params.get('product_id')      ?? undefined,
      requestId:      params.get('request_id')      ?? undefined,
      signature:      params.get('signature')       ?? undefined,
      rawQuery:       window.location.search,
    };

    verifyCheckout(redirectParams)
      .then(() => {
        router.replace('/billing');
      })
      .catch(() => {
        setError('We could not activate your plan. Please contact support if you were charged.');
      });
  }, [hasHydrated, isAuthenticated, router, verifyCheckout]);

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-[#F5F4F0] px-4">
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-8 max-w-md w-full text-center">
          <div className="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <svg className="w-6 h-6 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </div>
          <h1 className="text-lg font-semibold text-gray-900 mb-2">Activation failed</h1>
          <p className="text-sm text-gray-500 mb-6">{error}</p>
          <a
            href="/support"
            className="inline-block text-sm font-medium text-brand-purple hover:underline"
          >
            Contact support
          </a>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-[#F5F4F0]">
      <div className="text-center">
        <div className="w-10 h-10 border-2 border-brand-purple border-t-transparent rounded-full animate-spin mx-auto mb-4" />
        <p className="text-sm text-gray-500">Activating your plan…</p>
      </div>
    </div>
  );
}
