import { useFetch } from "../hooks";

interface SubMetric {
  raw: number;
  normalized: number;
  passed: boolean;
}

interface Dimension {
  score: number;
  passed: boolean;
  sub_metrics: Record<string, SubMetric>;
}

interface CompositeReport {
  composite_score: number;
  grade: string;
  deployment_phase: string;
  provider: string;
  model: string;
  dimensions: Record<string, Dimension>;
  stress_tests: Record<string, { name: string; passed: boolean; score: number }>;
}

interface ResultsResponse {
  composite: CompositeReport;
  sessions: Array<{ snapshot_id: string; agent: string; created_at: string }>;
}

export function Overview() {
  const { data, error, loading } = useFetch<ResultsResponse>("/api/v1/results");

  if (loading) return <div className="loading">Loading results…</div>;
  if (error) return <div className="error">Failed to load results: {error}</div>;
  if (!data) return null;

  const { composite, sessions } = data;
  const dims = Object.entries(composite.dimensions);
  const stressEntries = Object.entries(composite.stress_tests);
  const stressPassed = stressEntries.filter(([, v]) => v.passed).length;

  return (
    <>
      <h2>Overview</h2>

      <div className="cards">
        <div className="card">
          <div className="label">Grade</div>
          <div className={`value ${composite.grade.startsWith("A") || composite.grade.startsWith("S") ? "green" : composite.grade === "B" ? "yellow" : "red"}`}>
            {composite.grade}
          </div>
        </div>
        <div className="card">
          <div className="label">Composite Score</div>
          <div className="value">{(composite.composite_score * 100).toFixed(1)}%</div>
        </div>
        <div className="card">
          <div className="label">Stress Tests</div>
          <div className={`value ${stressPassed === stressEntries.length ? "green" : "red"}`}>
            {stressPassed}/{stressEntries.length}
          </div>
        </div>
        <div className="card">
          <div className="label">Deployment Phase</div>
          <div className="value" style={{ fontSize: "0.95rem" }}>
            {composite.deployment_phase}
          </div>
        </div>
      </div>

      <h2>Dimensions</h2>
      <table className="dim-table">
        <thead>
          <tr>
            <th>Dimension</th>
            <th>Score</th>
            <th>Status</th>
            <th>Sub-metrics</th>
          </tr>
        </thead>
        <tbody>
          {dims.map(([name, dim]) => (
            <tr key={name}>
              <td>{name}</td>
              <td>{(dim.score * 100).toFixed(1)}%</td>
              <td>
                <span className={`badge ${dim.passed ? "pass" : "fail"}`}>
                  {dim.passed ? "PASS" : "FAIL"}
                </span>
              </td>
              <td>
                {Object.entries(dim.sub_metrics).map(([sub, m]) => (
                  <div key={sub} style={{ fontSize: "0.8rem", color: "var(--text-muted)" }}>
                    {sub}: {(m.normalized * 100).toFixed(1)}%
                  </div>
                ))}
              </td>
            </tr>
          ))}
        </tbody>
      </table>

      {sessions.length > 0 && (
        <>
          <h2>Sessions</h2>
          <table>
            <thead>
              <tr>
                <th>Session ID</th>
                <th>Agent</th>
                <th>Created</th>
              </tr>
            </thead>
            <tbody>
              {sessions.map((s) => (
                <tr key={s.snapshot_id}>
                  <td style={{ fontFamily: "monospace", fontSize: "0.8rem" }}>
                    {s.snapshot_id}
                  </td>
                  <td>{s.agent}</td>
                  <td>{new Date(s.created_at).toLocaleString()}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </>
      )}
    </>
  );
}
