import type { ReactElement } from "react";
import { MetricsStrip, type MetricCell } from "@mosaic/ui";
import type { DashboardMetrics as DashboardMetricsData } from "@/lib/api/dashboard";

export interface DashboardMetricsProps {
  metrics?: DashboardMetricsData | undefined;
}

function formatNumber(n: number): string {
  return n.toLocaleString();
}

function buildCells(metrics: DashboardMetricsData): MetricCell[] {
  return [
    {
      label: "Active Agents",
      value: formatNumber(metrics.activeAgents),
      color: "var(--ms-blue-400)",
      trend: { direction: "neutral", text: "currently active" },
    },
    {
      label: "Tasks Completed",
      value: formatNumber(metrics.tasksCompleted),
      color: "var(--ms-teal-400)",
      trend: { direction: "neutral", text: `of ${formatNumber(metrics.totalTasks)} total` },
    },
    {
      label: "Total Tasks",
      value: formatNumber(metrics.totalTasks),
      color: "var(--ms-purple-400)",
      trend: { direction: "neutral", text: "across workspace" },
    },
    {
      label: "In Progress",
      value: formatNumber(metrics.tasksInProgress),
      color: "var(--ms-amber-400)",
      trend: { direction: "neutral", text: "tasks running" },
    },
    {
      label: "Error Rate",
      value: `${String(metrics.errorRate)}%`,
      color: "var(--ms-red-400)",
      trend: {
        direction: metrics.errorRate > 1 ? "up" : "down",
        text: metrics.errorRate > 1 ? "above threshold" : "within threshold",
      },
    },
    {
      label: "Active Projects",
      value: formatNumber(metrics.activeProjects),
      color: "var(--ms-cyan-500)",
      trend: { direction: "neutral", text: "in workspace" },
    },
  ];
}

const EMPTY_CELLS: MetricCell[] = [
  { label: "Active Agents", value: "0", color: "var(--ms-blue-400)" },
  { label: "Tasks Completed", value: "0", color: "var(--ms-teal-400)" },
  { label: "Total Tasks", value: "0", color: "var(--ms-purple-400)" },
  { label: "In Progress", value: "0", color: "var(--ms-amber-400)" },
  { label: "Error Rate", value: "0%", color: "var(--ms-red-400)" },
  { label: "Active Projects", value: "0", color: "var(--ms-cyan-500)" },
];

export function DashboardMetrics({ metrics }: DashboardMetricsProps): ReactElement {
  const cells = metrics ? buildCells(metrics) : EMPTY_CELLS;
  return <MetricsStrip cells={cells} />;
}
