'use client';

import React, { useEffect, useState, Suspense } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { apiRequest } from '@/lib/api';
import { useAuth } from '@/context/auth-context';
import { ShieldCheck, ShieldAlert, RefreshCw, ArrowRight } from 'lucide-react';
import Link from 'next/link';

function ConfirmPageContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const { user, updateUser } = useAuth();
  
  const reference = searchParams.get('reference');
  const [status, setStatus] = useState<'PENDING' | 'SUCCESS' | 'FAILED'>('PENDING');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!reference) {
      setError('Invalid reference number provided.');
      setLoading(false);
      return;
    }

    let pollCount = 0;
    const maxPolls = 15;

    const checkPayment = async () => {
      try {
        const data = await apiRequest(`api/subscription/payment-status/${reference}`);
        
        if (data.success && data.status === 'SUCCESS') {
          setStatus('SUCCESS');
          setLoading(false);
          
          if (data.business && user) {
            updateUser({
              ...user,
              subscriptionStatus: data.business.subscriptionStatus || 'ACTIVE',
              subscriptionPlan: data.business.subscriptionPlan,
              onboardingStep: data.business.onboardingStep || 'ONBOARDING_COMPLETED',
            });
          } else {
            const profile = await apiRequest('api/auth/me');
            updateUser(profile);
          }
          
          // Auto redirect after 3 seconds
          setTimeout(() => {
            router.push('/dashboard');
          }, 3000);
        } else if (data.status === 'FAILED') {
          setStatus('FAILED');
          setLoading(false);
        } else {
          // Keep polling
          pollCount++;
          if (pollCount < maxPolls) {
            setTimeout(checkPayment, 3000); // Check every 3 seconds
          } else {
            setLoading(false);
          }
        }
      } catch (err: any) {
        console.error('Failed to verify subscription status:', err);
        pollCount++;
        if (pollCount < maxPolls) {
          setTimeout(checkPayment, 3000);
        } else {
          setError('Verification timed out. If you paid, your account will be activated automatically once PesePay confirms.');
          setLoading(false);
        }
      }
    };

    checkPayment();
  }, [reference]);

  return (
    <div className="max-w-md mx-auto bg-[#1A1D24] border border-white/5 rounded-3xl p-8 text-center space-y-6 font-sans mt-12">
      
      {loading && (
        <div className="space-y-4 py-8">
          <RefreshCw className="w-12 h-12 text-emerald-500 animate-spin mx-auto" />
          <h2 className="text-xl font-bold text-white">Verifying Payment Status...</h2>
          <p className="text-xs text-gray-400">
            Please wait while we confirm your subscription payment with PesePay. Do not close or refresh this tab.
          </p>
        </div>
      )}

      {!loading && status === 'SUCCESS' && (
        <div className="space-y-4 py-4">
          <div className="w-16 h-16 rounded-full bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-center mx-auto">
            <ShieldCheck className="w-9 h-9 text-emerald-500" />
          </div>
          <h2 className="text-2xl font-black text-white">Subscription Activated!</h2>
          <p className="text-sm text-gray-300">
            Thank you! Your premium subscription plan has been successfully activated.
          </p>
          <div className="bg-emerald-500/12 border border-emerald-500/20 text-emerald-400 text-xs py-3 px-4 rounded-xl">
            Redirecting you to your WhatsApp Commerce Hub dashboard in a few seconds...
          </div>
          <Link
            href="/dashboard"
            className="w-full bg-emerald-600 hover:bg-emerald-700 text-white font-black text-xs uppercase tracking-wider py-4 rounded-xl transition-all shadow-md flex items-center justify-center gap-2 cursor-pointer mt-4"
          >
            <span>Go to Dashboard Now</span>
            <ArrowRight className="w-4 h-4" />
          </Link>
        </div>
      )}

      {!loading && (status === 'FAILED' || error) && (
        <div className="space-y-4 py-4">
          <div className="w-16 h-16 rounded-full bg-red-500/10 border border-red-500/20 flex items-center justify-center mx-auto">
            <ShieldAlert className="w-9 h-9 text-red-500" />
          </div>
          <h2 className="text-2xl font-black text-white">Payment Verification Failed</h2>
          <p className="text-sm text-gray-300">
            {error || 'We could not verify your payment at this moment. The transaction may have failed or was cancelled.'}
          </p>
          <Link
            href="/dashboard/billing"
            className="w-full bg-slate-900 hover:bg-slate-800 text-white border border-white/5 font-black text-xs uppercase tracking-wider py-4 rounded-xl transition-all shadow-md flex items-center justify-center gap-2 cursor-pointer mt-4"
          >
            <span>Return to Billing Page</span>
          </Link>
        </div>
      )}

      {!loading && status === 'PENDING' && !error && (
        <div className="space-y-4 py-4">
          <div className="w-16 h-16 rounded-full bg-yellow-500/10 border border-yellow-500/20 flex items-center justify-center mx-auto">
            <RefreshCw className="w-9 h-9 text-yellow-500 animate-spin" />
          </div>
          <h2 className="text-2xl font-black text-white">Payment Still Pending</h2>
          <p className="text-sm text-gray-300">
            PesePay is still processing your transaction. If you completed the checkout, your plan will be upgraded automatically within a few minutes.
          </p>
          <Link
            href="/dashboard"
            className="w-full bg-emerald-600 hover:bg-emerald-700 text-white font-black text-xs uppercase tracking-wider py-4 rounded-xl transition-all shadow-md flex items-center justify-center gap-2 cursor-pointer mt-4"
          >
            <span>Continue to Dashboard</span>
          </Link>
        </div>
      )}

    </div>
  );
}

export default function ConfirmPage() {
  return (
    <Suspense fallback={<div className="min-h-screen flex items-center justify-center bg-[#0d0f14] text-white">Loading Confirmation Page...</div>}>
      <ConfirmPageContent />
    </Suspense>
  );
}
