'use client';
import React, { useEffect, useState } from 'react';

interface PostStats {
  slug: string;
  cache_hits: number;
  cache_misses: number;
  last_interpret_time_ms: number;
  last_compile_time_ms: number;
}

export default function RustStatusPage() {
  const [stats, setStats] = useState<PostStats[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchStats = async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch('/api/admin/posts?rsparseinfo=1');
      if (!res.ok) throw new Error('Failed to fetch stats');
      const data = await res.json();
      setStats(data);
    } catch (e: any) {
      setError(e.message || 'Unknown error');
    } finally {
      setLoading(false);
    }
  };

  React.useEffect(() => {
    fetchStats();
    const interval = setInterval(fetchStats, 5000);
    return () => clearInterval(interval);
  }, []);

  return (
    <div className="p-8 max-w-4xl mx-auto">
      <h1 className="text-2xl font-bold mb-6">Rust Parser Status</h1>
      {loading && <div>Loading...</div>}
      {error && <div className="text-red-500">{error}</div>}
      {!loading && !error && (
        <div className="overflow-x-auto">
          <table className="min-w-full border border-gray-300 bg-white shadow-md rounded">
            <thead>
              <tr className="bg-gray-100">
                <th className="px-4 py-2 text-left">Slug</th>
                <th className="px-4 py-2 text-right">Cache Hits</th>
                <th className="px-4 py-2 text-right">Cache Misses</th>
                <th className="px-4 py-2 text-right">Last Interpret Time (ms)</th>
                <th className="px-4 py-2 text-right">Last Compile Time (ms)</th>
              </tr>
            </thead>
            <tbody>
              {stats.length === 0 ? (
                <tr><td colSpan={5} className="text-center py-4">No stats available.</td></tr>
              ) : (
                stats.map(stat => (
                  <tr key={stat.slug} className="border-t">
                    <td className="px-4 py-2 font-mono">{stat.slug}</td>
                    <td className="px-4 py-2 text-right">{stat.cache_hits}</td>
                    <td className="px-4 py-2 text-right">{stat.cache_misses}</td>
                    <td className="px-4 py-2 text-right">{stat.last_interpret_time_ms}</td>
                    <td className="px-4 py-2 text-right">{stat.last_compile_time_ms}</td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
} 