'use client';

import { useEffect, useState } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { useQueryClient } from '@tanstack/react-query';
import { API_BASE } from '@/lib/config';
import { CheckCircle2, XCircle, RefreshCw } from 'lucide-react';
import { useI18n } from '@/lib/i18n';

/**
 * /checkout/success
 * Stripe redirects here after a successful payment.
 * We call /api/v1/auth/checkout/sync to update the user plan in DB,
 * then redirect to /dashboard/profile?tab=subscription.
 */
export default function CheckoutSuccessPage() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const sessionId = searchParams.get('session_id');
  const queryClient = useQueryClient();
  const { t } = useI18n();

  const [status, setStatus] = useState<'syncing' | 'ok' | 'error'>('syncing');
  const [message, setMessage] = useState('');

  useEffect(() => {
    if (!sessionId) {
      // No session_id — just redirect to profile
      router.replace('/dashboard/profile?tab=subscription');
      return;
    }

    const token = localStorage.getItem('token');
    if (!token) {
      router.replace('/auth/login');
      return;
    }

    // Sync the checkout session to update plan in DB
    fetch(`${API_BASE}/api/v1/auth/checkout/sync?session_id=${sessionId}`, {
      headers: { Authorization: `Bearer ${token}` },
    })
      .then(async (res) => {
        let data: any = {};
        try { data = await res.json(); } catch { /* ignore */ }
        if (res.ok) {
          setStatus('ok');
          setMessage(
            data.data?.plan
              ? t('checkout.planActivated', { plan: data.data.plan })
              : t('checkout.subscriptionActivated')
          );
          queryClient.invalidateQueries({ queryKey: ['user', 'me'] });
          // Redirect after 2s
          setTimeout(() => router.replace('/dashboard/profile?tab=subscription'), 2000);
        } else {
          setStatus('error');
          setMessage(data.message ?? data.error ?? t('checkout.syncError'));
          setTimeout(() => router.replace('/dashboard/profile?tab=subscription'), 3000);
        }
      })
      .catch(() => {
        setStatus('error');
        setMessage(t('checkout.networkError'));
        setTimeout(() => router.replace('/dashboard/profile?tab=subscription'), 3000);
      });
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [sessionId]);

  return (
    <div className="min-h-screen flex items-center justify-center bg-background">
      <div className="flex flex-col items-center gap-6 p-12 rounded-3xl bg-white dark:bg-[#141414] shadow-2xl max-w-md w-full mx-4 text-center">
        {status === 'syncing' && (
          <>
            <RefreshCw className="w-12 h-12 text-brand-accent animate-spin" />
            <h1 className="text-2xl font-black uppercase tracking-tight">{t('checkout.activating')}</h1>
            <p className="text-sm text-muted-foreground">{t('checkout.activatingDesc')}</p>
          </>
        )}
        {status === 'ok' && (
          <>
            <CheckCircle2 className="w-12 h-12 text-emerald-500" />
            <h1 className="text-2xl font-black uppercase tracking-tight text-emerald-600">{t('checkout.paymentConfirmed')}</h1>
            <p className="text-sm text-muted-foreground">{message}</p>
            <p className="text-xs text-muted-foreground">{t('checkout.redirectingToProfile')}</p>
          </>
        )}
        {status === 'error' && (
          <>
            <XCircle className="w-12 h-12 text-amber-500" />
            <h1 className="text-2xl font-black uppercase tracking-tight">{t('checkout.paymentReceived')}</h1>
            <p className="text-sm text-muted-foreground">{message}</p>
            <p className="text-xs text-muted-foreground">{t('checkout.redirecting')}</p>
          </>
        )}
      </div>
    </div>
  );
}
