'use client';

import { useState, useEffect, Suspense } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { useAuthStore } from '@/lib/store';
import { useTranslation } from '@/lib/i18n';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000';

interface CheckoutResult {
  status: string;
  cc_amount: number;
  bonus_cc: number;
  total_cc: number;
  cc_balance: number;
}

function SuccessContent() {
  const { language } = useTranslation();
  const { token } = useAuthStore();
  const searchParams = useSearchParams();
  const router = useRouter();

  const [result, setResult] = useState<CheckoutResult | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const sessionId = searchParams.get('session_id');

  useEffect(() => {
    if (!sessionId) {
      setError('Invalid session');
      setLoading(false);
      return;
    }

    if (!token) {
      router.push('/login');
      return;
    }

    verifyPayment();
  }, [sessionId, token]);

  const verifyPayment = async () => {
    try {
      const response = await fetch(
        `${API_BASE_URL}/api/cc/checkout-success?session_id=${sessionId}`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }
      );

      if (response.ok) {
        const data = await response.json();
        setResult(data);
      } else {
        const err = await response.json();
        setError(err.detail || 'Failed to verify payment');
      }
    } catch (error) {
      console.error('Verification error:', error);
      setError('Failed to verify payment');
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-16 w-16 border-b-2 border-primary-500 mx-auto mb-4"></div>
          <p className="text-gray-600">
            {language === 'ko' ? '결제 확인 중...' : 'Verifying payment...'}
          </p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
        <div className="bg-white rounded-xl shadow-lg p-8 max-w-md w-full text-center">
          <div className="text-6xl mb-4">❌</div>
          <h1 className="text-2xl font-bold text-gray-800 mb-2">
            {language === 'ko' ? '결제 확인 실패' : 'Payment Verification Failed'}
          </h1>
          <p className="text-gray-600 mb-6">{error}</p>
          <Link
            href="/cc"
            className="inline-block px-6 py-3 bg-primary-600 text-white rounded-lg font-semibold hover:bg-primary-700 transition"
          >
            {language === 'ko' ? '다시 시도' : 'Try Again'}
          </Link>
        </div>
      </div>
    );
  }

  if (result?.status === 'completed') {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
        <div className="bg-white rounded-xl shadow-lg p-8 max-w-md w-full text-center">
          <div className="text-6xl mb-4">🎉</div>
          <h1 className="text-2xl font-bold text-gray-800 mb-2">
            {language === 'ko' ? '결제 완료!' : 'Payment Successful!'}
          </h1>
          <p className="text-gray-600 mb-6">
            {language === 'ko'
              ? 'CC가 성공적으로 충전되었습니다'
              : 'CC has been successfully credited to your account'}
          </p>

          <div className="bg-green-50 rounded-xl p-6 mb-6">
            <div className="text-sm text-green-600 mb-2">
              {language === 'ko' ? '충전된 CC' : 'CC Credited'}
            </div>
            <div className="text-4xl font-bold text-green-700">
              +{result.total_cc} CC
            </div>
            {result.bonus_cc > 0 && (
              <div className="text-sm text-green-600 mt-1">
                ({result.cc_amount} + {result.bonus_cc} bonus)
              </div>
            )}
          </div>

          <div className="bg-gray-50 rounded-xl p-4 mb-6">
            <div className="text-sm text-gray-500 mb-1">
              {language === 'ko' ? '현재 잔액' : 'Current Balance'}
            </div>
            <div className="text-2xl font-bold text-gray-800">
              {result.cc_balance.toFixed(1)} CC
            </div>
          </div>

          <div className="space-y-3">
            <Link
              href="/find-my-car"
              className="block w-full px-6 py-3 bg-primary-600 text-white rounded-lg font-semibold hover:bg-primary-700 transition"
            >
              {language === 'ko' ? '차량 추천 받기' : 'Get Car Recommendations'}
            </Link>
            <Link
              href="/cc"
              className="block w-full px-6 py-3 border border-gray-300 text-gray-700 rounded-lg font-semibold hover:bg-gray-50 transition"
            >
              {language === 'ko' ? '더 충전하기' : 'Purchase More CC'}
            </Link>
          </div>
        </div>
      </div>
    );
  }

  // Pending or other status
  return (
    <div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
      <div className="bg-white rounded-xl shadow-lg p-8 max-w-md w-full text-center">
        <div className="text-6xl mb-4">⏳</div>
        <h1 className="text-2xl font-bold text-gray-800 mb-2">
          {language === 'ko' ? '결제 처리 중' : 'Payment Processing'}
        </h1>
        <p className="text-gray-600 mb-6">
          {language === 'ko'
            ? '결제가 처리 중입니다. 잠시 후 다시 확인해주세요.'
            : 'Your payment is being processed. Please check back shortly.'}
        </p>
        <div className="space-y-3">
          <button
            onClick={() => verifyPayment()}
            className="w-full px-6 py-3 bg-primary-600 text-white rounded-lg font-semibold hover:bg-primary-700 transition"
          >
            {language === 'ko' ? '다시 확인' : 'Check Again'}
          </button>
          <Link
            href="/cc"
            className="block w-full px-6 py-3 border border-gray-300 text-gray-700 rounded-lg font-semibold hover:bg-gray-50 transition"
          >
            {language === 'ko' ? 'CC 충전 페이지로' : 'Back to CC Purchase'}
          </Link>
        </div>
      </div>
    </div>
  );
}

export default function CCSuccessPage() {
  return (
    <Suspense
      fallback={
        <div className="min-h-screen bg-gray-50 flex items-center justify-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-500"></div>
        </div>
      }
    >
      <SuccessContent />
    </Suspense>
  );
}
