"use client";

import type { CircuitBreakerStatus } from "@/lib/api/types";
import { formatTimeAgo } from "@/lib/format";
import { Button } from "@/components/ui/button";
import { StateBadge } from "./state-badge";
import type { CircuitState } from "./constants";

interface CircuitCardProps {
  breaker: CircuitBreakerStatus;
  onReset: (name: string) => void;
  isResetting: boolean;
}

export function CircuitCard({ breaker, onReset, isResetting }: CircuitCardProps) {
  const canReset = breaker.state !== "closed";

  return (
    <div className="rounded-lg border border-border bg-card p-4 transition-colors hover:bg-muted/50">
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <h3 className="font-mono text-sm font-medium text-foreground truncate">
          {breaker.name}
        </h3>
        <StateBadge state={breaker.state as CircuitState} />
      </div>

      {/* Stats */}
      <div className="grid grid-cols-3 gap-4 mb-4">
        <div>
          <p className="text-xs text-muted-foreground">Failures</p>
          <p className="text-lg font-semibold text-foreground">
            {breaker.failure_count}
          </p>
        </div>
        <div>
          <p className="text-xs text-muted-foreground">Successes</p>
          <p className="text-lg font-semibold text-foreground">
            {breaker.success_count}
          </p>
        </div>
        <div>
          <p className="text-xs text-muted-foreground">Timeout</p>
          <p className="text-lg font-semibold text-foreground">
            {breaker.timeout_seconds}s
          </p>
        </div>
      </div>

      {/* Last failure */}
      {breaker.last_failure && (
        <p className="text-xs text-muted-foreground mb-4 truncate">
          Last failure:{" "}
          <span className="text-foreground">
            &quot;{breaker.last_failure}&quot;
          </span>{" "}
          ({formatTimeAgo(breaker.last_state_change)})
        </p>
      )}

      {!breaker.last_failure && (
        <p className="text-xs text-muted-foreground mb-4">
          Last state change: {formatTimeAgo(breaker.last_state_change)}
        </p>
      )}

      {/* Actions */}
      {canReset && (
        <Button
          variant="outline"
          size="sm"
          onClick={() => onReset(breaker.name)}
          disabled={isResetting}
          className="w-full"
        >
          {isResetting ? "Resetting..." : "Reset Now"}
        </Button>
      )}
    </div>
  );
}
