import { useEffect, useState } from 'react';
import styles from '../styles/Dashboard.module.css';

interface MetricsData {
  totalPlayers: number;
  totalRuns: number;
  activePlayers24h: number;
  totalBossesDefeated: number;
  totalPrestigeLevelsGained: number;
}

const SUBGRAPH_URL = "https://api.studio.thegraph.com/query/75782/slay-the-moloch-base-mainnet/version/latest";

const Dashboard = () => {
  const [metrics, setMetrics] = useState<MetricsData>();

  useEffect(() => {
    const fetchMetrics = async () => {
      try {
        const response = await fetch(SUBGRAPH_URL, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            query: `{
              # Get global stats
              globalStat(id: "1") {
                totalPlayers
                totalBossesDefeated
                totalPrestigeLevels
                totalRuns
              }
              # Get active players in last 24h
              players(where: { lastRaidedAt_gt: "${Math.floor(Date.now() / 1000) - 86400}" }) {
                id
              }
            }`
          })
        });

        const data = await response.json();
        
        setMetrics({
          totalPlayers: parseInt(data.data.globalStat.totalPlayers),
          totalRuns: parseInt(data.data.globalStat.totalRuns),
          activePlayers24h: data.data.players.length,
          totalBossesDefeated: parseInt(data.data.globalStat.totalBossesDefeated),
          totalPrestigeLevels: parseInt(data.data.globalStat.totalPrestigeLevels)
        });
      } catch (error) {
        console.error("Error fetching metrics:", error);
      }
    };

    fetchMetrics();
    const interval = setInterval(fetchMetrics, 30000); // Refresh every 30 seconds
    return () => clearInterval(interval);
  }, []);

  return (
    <div className={styles.dashboard}>
      <div className={styles.metric}>
        <h3>Total Players</h3>
        <p>{metrics?.totalPlayers || 0}</p>
      </div>
      <div className={styles.metric}>
        <h3>Total Game Runs</h3>
        <p>{metrics?.totalRuns || 0}</p>
      </div>
      <div className={styles.metric}>
        <h3>Active Players (24h)</h3>
        <p>{metrics?.activePlayers24h || 0}</p>
      </div>
      <div className={styles.metric}>
        <h3>Total Bosses Defeated</h3>
        <p>{metrics?.totalBossesDefeated || 0}</p>
      </div>
      <div className={styles.metric}>
        <h3>Total Prestige Levels</h3>
        <p>{metrics?.totalPrestigeLevels || 0}</p>
      </div>
    </div>
  );
};

export default Dashboard;