"use client";

import type { CircuitBreakerStatus } from "@/lib/api/types";
import { cn } from "@/lib/utils";

interface CircuitSummaryProps {
  breakers: CircuitBreakerStatus[];
}

export function CircuitSummary({ breakers }: CircuitSummaryProps) {
  const closed = breakers.filter((b) => b.state === "closed").length;
  const halfOpen = breakers.filter((b) => b.state === "half_open").length;
  const open = breakers.filter((b) => b.state === "open").length;
  const total = breakers.length;

  // Calculate health status
  const healthStatus =
    open > 1
      ? "critical"
      : open === 1 || halfOpen > 0
        ? "degraded"
        : "healthy";

  const healthColors = {
    healthy: "text-emerald-600 dark:text-emerald-400",
    degraded: "text-amber-600 dark:text-amber-400",
    critical: "text-red-600 dark:text-red-400",
  };

  const healthLabels = {
    healthy: "All Systems Operational",
    degraded: "Degraded Performance",
    critical: "Critical Issues Detected",
  };

  // Calculate percentage safely (avoid division by zero)
  const getPercentage = (count: number): number => {
    if (total === 0) return 0;
    return (count / total) * 100;
  };

  return (
    <div className="rounded-lg border border-border bg-card p-4">
      <div className="flex items-center justify-between mb-4">
        <h3 className={cn("font-semibold", healthColors[healthStatus])}>
          {healthLabels[healthStatus]}
        </h3>
        <div className="flex items-center gap-4 text-sm">
          <span className="flex items-center gap-1.5">
            <span className="w-2 h-2 rounded-full bg-emerald-500" />
            <span className="text-muted-foreground">{closed} Closed</span>
          </span>
          <span className="flex items-center gap-1.5">
            <span className="w-2 h-2 rounded-full bg-amber-500" />
            <span className="text-muted-foreground">{halfOpen} Half-Open</span>
          </span>
          <span className="flex items-center gap-1.5">
            <span className="w-2 h-2 rounded-full bg-red-500" />
            <span className="text-muted-foreground">{open} Open</span>
          </span>
        </div>
      </div>

      {/* Health bar */}
      <div className="h-2 rounded-full bg-muted overflow-hidden flex">
        {total > 0 && closed > 0 && (
          <div
            className="bg-emerald-500 transition-all duration-300"
            style={{ width: `${getPercentage(closed)}%` }}
          />
        )}
        {total > 0 && halfOpen > 0 && (
          <div
            className="bg-amber-500 transition-all duration-300"
            style={{ width: `${getPercentage(halfOpen)}%` }}
          />
        )}
        {total > 0 && open > 0 && (
          <div
            className="bg-red-500 transition-all duration-300"
            style={{ width: `${getPercentage(open)}%` }}
          />
        )}
      </div>
    </div>
  );
}
