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

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

const DashboardPage: React.FC<DashboardPageProps> = ({ user, onLogout }) => {
  const [quests, setQuests] = useState<Quest[]>([]);
  const [members, setMembers] = useState<Member[]>([]);
  const [loading, setLoading] = useState(true);
  const [gold, setGold] = useState<number>(user.gold || 0);

  useEffect(() => {
    const loadData = async () => {
      try {
        const [questsData, membersData] = await Promise.all([
          apiService.getQuests(),
          apiService.getMembers(),
        ]);
        setQuests(questsData);
        setMembers(membersData);
        const currentGold = await apiService.getGoldBalance();
        setGold(currentGold);
      } catch (error) {
        console.error('Failed to load dashboard data:', error);
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, []);

  if (loading) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="text-center">
          <div className="text-4xl mb-4">🧝</div>
          <p className="text-text-primary font-readable">Opening the gates of Rivendell...</p>
        </div>
      </div>
    );
  }

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

      {/* Main Content */}
      <div className="max-w-7xl mx-auto px-4 py-8">
        <Dashboard quests={quests} members={members} user={user} />
      </div>
    </div>
  );
};

export default DashboardPage;
