// components/system.jsx — SystemPanel: merged Models + Providers + Diagnostics.
// Depends on: React (useState, useEffect, useCallback), Card, StatusBadge, get from api.js,
//             ModelsTable from models.jsx, ProvidersCard from overview.jsx,
//             DiagnosticsPanel from diagnostics.jsx

function useSystemData() {
  const [models, setModels] = useState([]);
  const [providers, setProviders] = useState([]);
  const [health, setHealth] = useState(null);
  const [loading, setLoading] = useState(true);

  const refresh = useCallback(async () => {
    setLoading(true);
    const [m, p, h] = await Promise.all([
      get("/v1/models"),
      get("/dashboard/providers"),
      get("/health"),
    ]);
    setModels(m?.data || []);
    setProviders(p?.providers || []);
    setHealth(h);
    setLoading(false);
  }, []);

  useEffect(() => { refresh(); }, [refresh]);

  return { models, providers, health, loading, refresh };
}

function SystemPanel({ initialSection = "overview" }) {
  const { models, providers, health, loading, refresh } = useSystemData();
  const [section, setSection] = useState(initialSection); // overview | models | diagnostics | human

  useEffect(() => {
    setSection(initialSection);
  }, [initialSection]);

  if (loading) {
    return <Card title="System"><p className="text-gray-400 text-sm">Loading…</p></Card>;
  }

  const activeProviders = providers.filter(p => p.has_key);

  return (
    <div className="space-y-4">
      {/* Section switcher */}
      <div className="flex items-center gap-2">
        {[
          { id: "overview", label: "Overview" },
          { id: "models", label: `Models (${models.length})` },
          { id: "diagnostics", label: "Diagnostics" },
          { id: "human", label: "Human" },
        ].map(s => (
          <button key={s.id} onClick={() => setSection(s.id)}
            className={`px-3 py-1.5 text-sm rounded-lg font-medium transition-colors ${
              section === s.id
                ? "bg-blue-600 text-white"
                : "bg-gray-100 text-gray-600 hover:bg-gray-200"
            }`}>{s.label}</button>
        ))}
        <button onClick={refresh} className="ml-auto text-xs px-3 py-1 bg-gray-100 text-gray-600 rounded hover:bg-gray-200">
          ↻ Refresh
        </button>
      </div>

      {/* Overview section */}
      {section === "overview" && (
        <div className="space-y-4">
          {/* Health summary */}
          <Card title="System Health">
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="text-center">
                <div className="text-2xl font-bold text-gray-900">{health?.version || "?"}</div>
                <div className="text-xs text-gray-500">Version</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-emerald-600">{activeProviders.length}</div>
                <div className="text-xs text-gray-500">Active Providers</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-blue-600">{models.length}</div>
                <div className="text-xs text-gray-500">Available Models</div>
              </div>
              <div className="text-center">
                <StatusBadge ok={!!health} label={health ? "Healthy" : "Down"} />
              </div>
            </div>
          </Card>

          {/* Providers */}
          <Card title={`Providers (${activeProviders.length}/${providers.length} active)`}>
            <div className="space-y-2">
              {providers.map(p => (
                <div key={p.name} className="flex items-center justify-between py-2 border-b border-gray-100 last:border-0">
                  <div className="flex items-center gap-2">
                    <span className={`w-2 h-2 rounded-full ${p.has_key ? "bg-emerald-500" : "bg-gray-300"}`} />
                    <span className="font-medium text-sm text-gray-900">{p.name}</span>
                  </div>
                  <div className="flex items-center gap-3 text-xs text-gray-500">
                    <span>{p.model_count} models</span>
                    <span className={p.has_key ? "text-emerald-600" : "text-gray-400"}>
                      {p.has_key ? "✓ Key configured" : "✗ No key"}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          </Card>

          {/* Quick model list — top 10 */}
          <Card title="Top Models">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
              {models.slice(0, 10).map(m => (
                <div key={m.id} className="flex items-center justify-between py-1.5 px-3 bg-gray-50 rounded text-sm">
                  <span className="font-mono text-xs text-gray-700 truncate">{m.id}</span>
                  <span className="text-xs text-gray-400">{m.owned_by}</span>
                </div>
              ))}
            </div>
            {models.length > 10 && (
              <button onClick={() => setSection("models")} className="mt-2 text-xs text-blue-600 hover:text-blue-700">
                Show all {models.length} models →
              </button>
            )}
          </Card>
          <ToolHealthPanel />
        </div>
      )}

      {/* Models section — full table */}
      {section === "models" && (
        <Card title={`All Models (${models.length})`}>
          <ModelsTable models={models} />
        </Card>
      )}

      {/* Diagnostics section — reuse existing panel */}
      {section === "diagnostics" && (
        <DiagnosticsPanel />
      )}

      {section === "human" && (
        <HumanTaskPanel />
      )}
    </div>
  );
}
