'use client';

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

export default function TestRewardPage() {
  const { user } = useAuth();
  const [reward, setReward] = useState<Reward | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [inventoryStatus, setInventoryStatus] = useState<'idle' | 'pending' | 'success' | 'error'>('idle');
  const [receiptId, setReceiptId] = useState('test-receipt-123');
  const [sessionId, setSessionId] = useState('cs_test_1234567890');
  const [stripeReceiptId, setStripeReceiptId] = useState<string | null>(null);

  const handleGetRandomReward = async () => {
    setIsLoading(true);
    setError(null);
    setReward(null);
    setInventoryStatus('idle');
    setStripeReceiptId(null);

    try {
      const randomReward = await fetchRandomReward();
      if (randomReward) {
        setReward(randomReward);
      }
    } catch (err) {
      console.error('Error fetching random reward:', err);
      setError(err instanceof Error ? err.message : 'Failed to fetch reward');
    } finally {
      setIsLoading(false);
    }
  };

  const handleGetReceiptId = async () => {
    if (!sessionId) {
      setError('Please enter a session ID');
      return;
    }

    try {
      const receipt = await getReceiptId(sessionId);
      setStripeReceiptId(receipt);
      if (receipt) {
        console.log('Got receipt ID from Stripe:', receipt);
      } else {
        console.log('No receipt ID found for session:', sessionId);
      }
    } catch (err) {
      console.error('Error getting receipt ID:', err);
      setError(err instanceof Error ? err.message : 'Failed to get receipt ID');
    }
  };

  const handleAddToInventory = async () => {
    if (!reward || !user?.uid) {
      setError('No reward or user available');
      return;
    }

    setInventoryStatus('pending');
    setError(null);

    // Use Stripe receipt ID if available, otherwise use manual receipt ID
    const finalReceiptId = stripeReceiptId || receiptId;

    try {
      const success = await addInventoryItem(finalReceiptId, user.uid, reward.id);
      if (success) {
        setInventoryStatus('success');
      } else {
        setInventoryStatus('error');
        setError('Failed to add to inventory');
      }
    } catch (err) {
      console.error('Error adding to inventory:', err);
      setInventoryStatus('error');
      setError(err instanceof Error ? err.message : 'Failed to add to inventory');
    }
  };

  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">
          {/* Page Header */}
          <div className="text-center mb-8">
            <h1 className="text-3xl font-bold mb-2">Test Random Reward</h1>
            <p className="text-foreground/60">
              Test the random reward API functionality with Stripe receipt IDs
            </p>
          </div>

          {/* Input Fields */}
          <div className="text-center mb-8 space-y-4">
            <div>
              <label htmlFor="sessionId" className="block text-sm font-medium mb-2">
                Stripe Session ID (for testing receipt ID):
              </label>
              <input
                id="sessionId"
                type="text"
                value={sessionId}
                onChange={(e) => setSessionId(e.target.value)}
                className="px-4 py-2 rounded-lg bg-foreground/5 border border-foreground/10 text-sm focus:outline-none focus:ring-2 focus:ring-purple-500"
                placeholder="Enter Stripe session ID"
              />
            </div>
            
            <div>
              <label htmlFor="receiptId" className="block text-sm font-medium mb-2">
                Manual Receipt ID (fallback):
              </label>
              <input
                id="receiptId"
                type="text"
                value={receiptId}
                onChange={(e) => setReceiptId(e.target.value)}
                className="px-4 py-2 rounded-lg bg-foreground/5 border border-foreground/10 text-sm focus:outline-none focus:ring-2 focus:ring-purple-500"
                placeholder="Enter manual receipt ID"
              />
            </div>
          </div>

          {/* Test Buttons */}
          <div className="text-center mb-8 space-y-4">
            <button
              onClick={handleGetRandomReward}
              disabled={isLoading}
              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 disabled:opacity-50 mr-4"
            >
              {isLoading ? 'Fetching...' : 'Get Random Reward'}
            </button>

            <button
              onClick={handleGetReceiptId}
              disabled={!sessionId}
              className="px-6 py-3 rounded-lg bg-gradient-to-r from-blue-600 to-cyan-600 text-white font-semibold hover:opacity-90 transition-opacity disabled:opacity-50 mr-4"
            >
              Get Receipt ID from Stripe
            </button>

            {reward && user && (
              <button
                onClick={handleAddToInventory}
                disabled={inventoryStatus === 'pending'}
                className="px-6 py-3 rounded-lg bg-gradient-to-r from-green-600 to-blue-600 text-white font-semibold hover:opacity-90 transition-opacity disabled:opacity-50"
              >
                {inventoryStatus === 'pending' ? 'Adding...' : 'Add to Inventory'}
              </button>
            )}
          </div>

          {/* Receipt ID Display */}
          {stripeReceiptId && (
            <div className="text-center mb-8">
              <div className="bg-blue-500/10 border border-blue-500/20 rounded-lg p-4">
                <p className="text-blue-500 text-sm">
                  ✅ Stripe Receipt ID: <span className="font-mono">{stripeReceiptId}</span>
                </p>
              </div>
            </div>
          )}

          {/* Error Message */}
          {error && (
            <div className="text-center mb-8">
              <div className="bg-red-500/10 border border-red-500/20 rounded-lg p-4">
                <p className="text-red-500">{error}</p>
              </div>
            </div>
          )}

          {/* Inventory Status */}
          {inventoryStatus !== 'idle' && (
            <div className="text-center mb-8">
              <div className={`p-3 rounded-lg border ${
                inventoryStatus === 'success' ? 'bg-green-500/10 border-green-500/20' :
                inventoryStatus === 'error' ? 'bg-red-500/10 border-red-500/20' :
                'bg-yellow-500/10 border-yellow-500/20'
              }`}>
                <p className={`text-sm ${
                  inventoryStatus === 'success' ? 'text-green-500' :
                  inventoryStatus === 'error' ? 'text-red-500' :
                  'text-yellow-500'
                }`}>
                  {inventoryStatus === 'success' ? '✅ Added to inventory successfully!' :
                   inventoryStatus === 'error' ? '❌ Failed to add to inventory' :
                   '⏳ Adding to inventory...'}
                </p>
              </div>
            </div>
          )}

          {/* Reward Display */}
          {reward && (
            <div className="text-center">
              <h2 className="text-2xl font-bold mb-6">Random Reward</h2>
              <div className="max-w-sm mx-auto">
                <RewardCard reward={reward} />
              </div>
            </div>
          )}

          {/* API Info */}
          <div className="mt-12 bg-foreground/5 rounded-xl p-6">
            <h3 className="text-lg font-semibold mb-4">API Information</h3>
            <div className="space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-foreground/60">Random Reward Endpoint:</span>
                <span className="font-mono">/api/get-random-reward</span>
              </div>
              <div className="flex justify-between">
                <span className="text-foreground/60">Get Receipt ID Endpoint:</span>
                <span className="font-mono">/api/get-receipt-id</span>
              </div>
              <div className="flex justify-between">
                <span className="text-foreground/60">Add Inventory Endpoint:</span>
                <span className="font-mono">/api/add-inventory-item</span>
              </div>
              <div className="flex justify-between">
                <span className="text-foreground/60">Stripe Webhook:</span>
                <span className="font-mono">/api/webhooks/stripe</span>
              </div>
              <div className="flex justify-between">
                <span className="text-foreground/60">External Reward API:</span>
                <span className="font-mono text-xs">vps.playpoolstudios.com/boxy/api/get_random_reward.php</span>
              </div>
              <div className="flex justify-between">
                <span className="text-foreground/60">External Inventory API:</span>
                <span className="font-mono text-xs">vps.playpoolstudios.com/boxy/api/add_inventory_item.php</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
} 