// Analytics Page Component
const AnalyticsPage = () => {
  const { Box, Typography, Card, CardContent, Button } = MaterialUI;

  // --- State for counts and refresh logic ---
  const [getCounts, setGetCounts] = React.useState({
    GET: { sinceRestart: 0, pastHour: 0, past10min: 0 },
    POST: { sinceRestart: 0, pastHour: 0, past10min: 0 },
    OTHER: { sinceRestart: 0, pastHour: 0, past10min: 0 }
  });
  const [lastUpdated, setLastUpdated] = React.useState(new Date().toLocaleTimeString());
  const [uptimeMs, setUptimeMs] = React.useState(0);
  const uptimeRef = React.useRef(0);

  // Helper to map API keys to table keys
  function mapApiToTable(apiData) {
    return {
      GET: {
        sinceRestart: apiData.GET?.total ?? 0,
        pastHour: apiData.GET?.['1hr'] ?? 0,
        past10min: apiData.GET?.['10min'] ?? 0
      },
      POST: {
        sinceRestart: apiData.POST?.total ?? 0,
        pastHour: apiData.POST?.['1hr'] ?? 0,
        past10min: apiData.POST?.['10min'] ?? 0
      },
      OTHER: {
        sinceRestart: apiData.OTHER?.total ?? 0,
        pastHour: apiData.OTHER?.['1hr'] ?? 0,
        past10min: apiData.OTHER?.['10min'] ?? 0
      }
    };
  }

  // Fetch stats every 20s, but update uptime locally every second
  React.useEffect(() => {
    let uptimeInterval;
    async function fetchStats() {
      try {
        const res = await fetch('/data/analytics/stats');
        if (!res.ok) throw new Error('Failed to fetch analytics stats');
        const data = await res.json();
        setGetCounts(mapApiToTable(data));
        setUptimeMs(data.uptime_ms ?? 0);
        uptimeRef.current = data.uptime_ms ?? 0;
        setLastUpdated(new Date().toLocaleTimeString());
      } catch (e) {
        // Optionally handle error
      }
    }
    fetchStats();
    const statsInterval = setInterval(fetchStats, 20000); // 20 seconds
    // Local uptime increment every second
    uptimeInterval = setInterval(() => {
      setUptimeMs(prev => prev + 1000);
    }, 1000);
    return () => {
      clearInterval(statsInterval);
      clearInterval(uptimeInterval);
    };
  }, []);

  // Helper to format uptime in d h m s
  function formatUptime(ms) {
    const sec = Math.floor(ms / 1000) % 60;
    const min = Math.floor(ms / 1000 / 60) % 60;
    const hr = Math.floor(ms / 1000 / 60 / 60) % 24;
    const day = Math.floor(ms / 1000 / 60 / 60 / 24);
    return `${day}d ${hr}h ${min}m ${sec}s`;
  }

  return (
    <Box>
      <Typography variant="h4" gutterBottom>
        Server Analytics
      </Typography>

      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Typography variant="h6" gutterBottom>
            Uptime
          </Typography>
          <Typography variant="h5" sx={{ mt: 1, mb: 1 }}>
            {formatUptime(uptimeMs)}
          </Typography>
        </CardContent>
      </Card>

      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Typography variant="h6" gutterBottom>
            Requests
          </Typography>
          <Box sx={{ mt: 2, mb: 1 }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'center' }}>
              <thead>
                <tr>
                  <th style={{ width: '25%' }}></th>
                  <th style={{ width: '25%' }}>Restart</th>
                  <th style={{ width: '25%' }}>Hour</th>
                  <th style={{ width: '25%' }}>10 Min</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td style={{ fontWeight: 500, textAlign: 'left' }}>GET</td>
                  <td>{getCounts.GET.sinceRestart}</td>
                  <td>{getCounts.GET.pastHour}</td>
                  <td>{getCounts.GET.past10min}</td>
                </tr>
                <tr>
                  <td style={{ fontWeight: 500, textAlign: 'left' }}>POST</td>
                  <td>{getCounts.POST.sinceRestart}</td>
                  <td>{getCounts.POST.pastHour}</td>
                  <td>{getCounts.POST.past10min}</td>
                </tr>
                <tr>
                  <td style={{ fontWeight: 500, textAlign: 'left' }}>OTHER</td>
                  <td>{getCounts.OTHER.sinceRestart}</td>
                  <td>{getCounts.OTHER.pastHour}</td>
                  <td>{getCounts.OTHER.past10min}</td>
                </tr>
              </tbody>
            </table>
          </Box>
          <Typography variant="caption" color="text.secondary">
            Last updated: {lastUpdated}
          </Typography>
        </CardContent>
      </Card>

    </Box>
  );
};

// Make component available globally
window.AnalyticsPage = AnalyticsPage;