'use client';

import { useState, useEffect } from 'react';
import { useSearchParams } from 'next/navigation';
import { useAuth } from '../../context/AuthContext';
import Header from '../../components/Header';
import RewardCard from '../../components/RewardCard';
import { fetchRandomReward, getReceiptId, addInventoryItem, type Reward } from '../../lib/rewards';

export default function SuccessPage() {
  const { user } = useAuth();
  const searchParams = useSearchParams();
  const [isOpening, setIsOpening] = useState(true);
  const [reward, setReward] = useState<Reward | null>(null);
  const [showReward, setShowReward] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [inventoryStatus, setInventoryStatus] = useState<'pending' | 'success' | 'error'>('pending');
  const [receiptId, setReceiptId] = useState<string | null>(null);

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

  useEffect(() => {
    // Simulate box opening animation
    const timer = setTimeout(async () => {
      setIsOpening(false);
      
      try {
        // Fetch real random reward from API
        const randomReward = await fetchRandomReward();
        if (randomReward) {
          setReward(randomReward);
          setShowReward(true);
          
          // Get receipt ID from Stripe if session ID is available
          if (sessionId) {
            try {
              console.log('Getting receipt ID for session:', sessionId);
              const stripeReceiptId = await getReceiptId(sessionId);
              
              if (stripeReceiptId) {
                setReceiptId(stripeReceiptId);
                console.log('Got receipt ID from Stripe:', stripeReceiptId);
                
                // Add reward to inventory with actual receipt ID
                if (user?.uid) {
                  try {
                    console.log('Adding reward to inventory:', {
                      receiptId: stripeReceiptId,
                      userId: user.uid,
                      rewardId: randomReward.id
                    });
                    
                    const success = await addInventoryItem(stripeReceiptId, user.uid, randomReward.id);
                    if (success) {
                      setInventoryStatus('success');
                      console.log('Reward added to inventory successfully');
                    } else {
                      setInventoryStatus('error');
                      setError('Something went wrong');
                      setShowReward(false);
                      setReward(null);
                    }
                  } catch (inventoryError) {
                    console.error('Error adding to inventory:', inventoryError);
                    setInventoryStatus('error');
                    setError('Something went wrong');
                    setShowReward(false);
                    setReward(null);
                  }
                }
              } else {
                console.log('No receipt ID found for session, using session ID as fallback');
                // Fallback to using session ID if no receipt ID is found
                if (user?.uid) {
                  try {
                    const success = await addInventoryItem(sessionId, user.uid, randomReward.id);
                    if (success) {
                      setInventoryStatus('success');
                    } else {
                      setInventoryStatus('error');
                      setError('Something went wrong');
                      setShowReward(false);
                      setReward(null);
                    }
                  } catch (inventoryError) {
                    console.error('Error adding to inventory with fallback:', inventoryError);
                    setInventoryStatus('error');
                    setError('Something went wrong');
                    setShowReward(false);
                    setReward(null);
                  }
                }
              }
            } catch (receiptError) {
              console.error('Error getting receipt ID:', receiptError);
              // Continue with fallback to session ID
              if (user?.uid) {
                try {
                  const success = await addInventoryItem(sessionId!, user.uid, randomReward.id);
                  if (success) {
                    setInventoryStatus('success');
                  } else {
                    setInventoryStatus('error');
                    setError('Something went wrong');
                    setShowReward(false);
                    setReward(null);
                  }
                } catch (inventoryError) {
                  console.error('Error adding to inventory with fallback:', inventoryError);
                  setInventoryStatus('error');
                  setError('Something went wrong');
                  setShowReward(false);
                  setReward(null);
                }
              }
            }
          }
        }
      } catch (err) {
        console.error('Error fetching random reward:', err);
        setError(err instanceof Error ? err.message : 'Failed to fetch reward');
      }
    }, 3000);

    return () => clearTimeout(timer);
  }, [sessionId, user?.uid]);

  if (!user) {
    return (
      <>
        <Header />
        <div className="min-h-screen bg-gradient-to-b from-background to-background/95 pt-16">
          <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8 text-center">
            <h1 className="text-2xl font-bold mb-4">Access Denied</h1>
            <p className="text-foreground/60">Please sign in to view this page.</p>
          </div>
        </div>
      </>
    );
  }

  // Show only error message if there's an error
  if (error) {
    return (
      <>
        <Header />
        <div className="min-h-screen bg-gradient-to-b from-background to-background/95 pt-16">
          <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8 text-center">
            <div className="text-6xl mb-4">❌</div>
            <h1 className="text-3xl font-bold mb-4">Something went wrong</h1>
            <p className="text-foreground/60 mb-8">
              {error}
            </p>
            <div className="flex flex-col sm:flex-row gap-4 justify-center">
              <button
                onClick={() => window.location.href = '/boxes'}
                className="px-6 py-3 rounded-lg bg-gradient-to-r from-purple-600 to-pink-600 text-white font-semibold hover:opacity-90 transition-opacity"
              >
                Back to Boxes
              </button>
              <button
                onClick={() => window.location.reload()}
                className="px-6 py-3 rounded-lg border border-foreground/20 hover:bg-foreground/5 transition-colors"
              >
                Try Again
              </button>
            </div>
          </div>
        </div>
      </>
    );
  }

  return (
    <>
      <Header />
      <div className="min-h-screen bg-gradient-to-b from-background to-background/95 pt-16">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          {/* Success Header */}
          <div className="text-center mb-8">
            <div className="text-6xl mb-4">🎉</div>
            <h1 className="text-3xl font-bold mb-2">Payment Successful!</h1>
            <p className="text-foreground/60">
              Your mystery box is being opened...
            </p>
          </div>

          {/* Box Opening Animation */}
          {isOpening && (
            <div className="text-center py-12">
              <div className="inline-block animate-bounce">
                <div className="text-8xl mb-4">🎁</div>
              </div>
              <p className="text-lg text-foreground/60">Opening your box...</p>
            </div>
          )}

          {/* Reward Reveal */}
          {showReward && reward && (
            <div className="text-center">
              <div className="bg-gradient-to-br from-purple-500/10 to-pink-500/10 rounded-2xl p-8 mb-8">
                <div className="text-6xl mb-4">✨</div>
                <h2 className="text-2xl font-bold mb-2">Congratulations!</h2>
                <p className="text-foreground/60 mb-6">
                  You found something amazing!
                </p>
                
                {/* Reward Card */}
                <div className="max-w-sm mx-auto">
                  <RewardCard reward={reward} />
                </div>

                {/* Inventory Status */}
                {inventoryStatus === 'success' && (
                  <div className="mt-4 p-3 bg-green-500/10 border border-green-500/20 rounded-lg">
                    <p className="text-green-500 text-sm">✅ Added to your inventory!</p>
                  </div>
                )}
              </div>

              {/* Action Buttons */}
              <div className="flex flex-col sm:flex-row gap-4 justify-center">
                <button
                  onClick={() => window.location.href = '/inventory'}
                  className="px-6 py-3 rounded-lg bg-gradient-to-r from-purple-600 to-pink-600 text-white font-semibold hover:opacity-90 transition-opacity"
                >
                  View in Inventory
                </button>
                <button
                  onClick={() => window.location.href = '/boxes'}
                  className="px-6 py-3 rounded-lg border border-foreground/20 hover:bg-foreground/5 transition-colors"
                >
                  Open Another Box
                </button>
              </div>
            </div>
          )}

          {/* Transaction Details */}
          <div className="mt-12 bg-foreground/5 rounded-xl p-6">
            <h3 className="text-lg font-semibold mb-4">Transaction Details</h3>
            <div className="space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-foreground/60">Session ID:</span>
                <span className="font-mono">{sessionId}</span>
              </div>
              {receiptId && (
                <div className="flex justify-between">
                  <span className="text-foreground/60">Receipt ID:</span>
                  <span className="font-mono">{receiptId}</span>
                </div>
              )}
              <div className="flex justify-between">
                <span className="text-foreground/60">Box ID:</span>
                <span className="font-mono">{boxId}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-foreground/60">User:</span>
                <span>{user.email}</span>
              </div>
              {reward && (
                <div className="flex justify-between">
                  <span className="text-foreground/60">Reward ID:</span>
                  <span className="font-mono">{reward.id}</span>
                </div>
              )}
              <div className="flex justify-between">
                <span className="text-foreground/60">Inventory Status:</span>
                <span className={`font-medium ${
                  inventoryStatus === 'success' ? 'text-green-500' :
                  inventoryStatus === 'error' ? 'text-red-500' :
                  'text-yellow-500'
                }`}>
                  {inventoryStatus === 'success' ? 'Added' :
                   inventoryStatus === 'error' ? 'Failed' :
                   'Pending'}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
} 