import React, { useEffect, useState } from 'react';
import { apiService } from '../services/api';
import { analyticsService } from '../services/analyticsService';
import { BargainStats, InventoryItem, User, Quest } from '../types';
import AppHeader from '../components/AppHeader';

interface InventoryPageProps {
  user: User;
  onLogout: () => void;
}

const InventoryPage: React.FC<InventoryPageProps> = ({ user, onLogout }) => {
  const [inventory, setInventory] = useState<InventoryItem[]>([]);
  const [quests, setQuests] = useState<Quest[]>([]);
  const [stats, setStats] = useState<BargainStats>({
    purchased_count: 0,
    best_bargain_percent: 0,
    average_savings_percent: 0,
  });
  const [gold, setGold] = useState<number>(user.gold || 0);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const load = async () => {
      try {
        const [items, currentStats, currentGold, questsData] = await Promise.all([
          apiService.getInventory(),
          apiService.getBargainStats(),
          apiService.getGoldBalance(),
          apiService.getQuests(),
        ]);
        setInventory(items);
        setStats(currentStats);
        setGold(currentGold);
        setQuests(questsData);
        
        // Track inventory viewed with item count
        analyticsService.trackInventoryViewed(items.length);
      } catch (error) {
        console.error('Failed to load inventory:', error);
      } finally {
        setLoading(false);
      }
    };

    load();
  }, []);

  if (loading) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <p className="text-text-primary font-readable">Gathering your purchased relics...</p>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      {/* Header */}
      <AppHeader
        page="inventory"
        gold={gold}
        completedQuests={quests.filter(q => q.status === 'it_is_done').length}
        averageSavings={stats.average_savings_percent}
        onLogout={onLogout}
      />

      <div className="max-w-7xl mx-auto px-4 py-8 space-y-6">
        <h1 className="font-epic text-3xl text-gold">Inventory</h1>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-4" data-tour="inventory-stats">
          <div className="bg-parchment-light rounded-lg p-4 border border-gold-dark/30">
            <p className="text-xs uppercase text-text-secondary">Items Purchased</p>
            <p className="font-epic text-2xl text-forest-dark">{stats.purchased_count}</p>
          </div>
          <div className="bg-parchment-light rounded-lg p-4 border border-gold-dark/30">
            <p className="text-xs uppercase text-text-secondary">Best Bargain</p>
            <p className="font-epic text-2xl text-forest-dark">{stats.best_bargain_percent.toFixed(2)}%</p>
          </div>
          <div className="bg-parchment-light rounded-lg p-4 border border-gold-dark/30">
            <p className="text-xs uppercase text-text-secondary">Average Savings</p>
            <p className="font-epic text-2xl text-forest-dark">{stats.average_savings_percent.toFixed(2)}%</p>
          </div>
        </div>

        <div className="bg-parchment-light rounded-lg border border-gold-dark/30 overflow-hidden">
          <table className="w-full">
            <thead className="bg-forest/10">
              <tr>
                <th className="text-left p-3">Item</th>
                <th className="text-left p-3">Seller</th>
                <th className="text-left p-3">Paid</th>
                <th className="text-left p-3">Real Price</th>
                <th className="text-left p-3">Deal %</th>
              </tr>
            </thead>
            <tbody>
              {inventory.length === 0 ? (
                <tr>
                  <td colSpan={5} className="p-4 text-text-secondary">
                    No purchased items yet. Visit character markers on the map to start bargaining.
                  </td>
                </tr>
              ) : (
                inventory.map((entry) => (
                  <tr key={entry.id} className="border-t border-gold-dark/20">
                    <td className="p-3">{entry.item_name}</td>
                    <td className="p-3 capitalize">{entry.owner_character}</td>
                    <td className="p-3">{entry.paid_price} Gold</td>
                    <td className="p-3">{entry.base_price_revealed} Gold</td>
                    <td className={`p-3 ${entry.savings_percent >= 0 ? 'text-green-700' : 'text-red-700'}`}>
                      {entry.savings_percent.toFixed(2)}%
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

export default InventoryPage;
