import { useEffect, useState } from "react";
import { Alert } from "antd";
import { apiClient } from "@shared/api/client";

type SyncRow = {
  enterprise_id: string;
  name: string;
  slug: string;
  outbox_pending: number;
  conflicts_pending: number;
  max_event_seq: number;
  hubs: Array<{ name: string; sync_lag: number; last_seen: string | null }>;
};

export function AdminSyncPanel(): JSX.Element {
  const [rows, setRows] = useState<SyncRow[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    void (async () => {
      try {
        const { data } = await apiClient.get<SyncRow[]>("/api/v1/admin/sync-metrics");
        setRows(Array.isArray(data) ? data : []);
        setError(null);
      } catch (loadError) {
        const message = loadError instanceof Error ? loadError.message : "Failed to load sync metrics";
        setError(message);
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  if (loading) {
    return <p className="wesp-admin-block">Loading sync metrics...</p>;
  }

  if (error) {
    return <Alert type="error" message={error} />;
  }

  return (
    <div>
      <h2>Sync metrics</h2>
      {rows.length === 0 ? <p className="text-muted">No enterprises yet.</p> : null}
      {rows.map((r) => (
        <div key={r.enterprise_id} style={{ marginBottom: 16 }}>
          <strong>{r.name}</strong> — outbox {r.outbox_pending}, conflicts {r.conflicts_pending}, seq{" "}
          {r.max_event_seq}
          <ul>
            {r.hubs.map((h) => (
              <li key={h.name}>
                {h.name}: lag {h.sync_lag}
                {h.last_seen ? ` · ${h.last_seen}` : " · offline"}
              </li>
            ))}
          </ul>
        </div>
      ))}
    </div>
  );
}
