"use client";

import { useState } from "react";
import type { CircuitBreakerStatus } from "@/lib/api/types";
import { CircuitCard } from "./circuit-card";

interface CircuitListProps {
  breakers: CircuitBreakerStatus[];
  onReset: (name: string) => Promise<void>;
}

export function CircuitList({ breakers, onReset }: CircuitListProps) {
  const [resettingName, setResettingName] = useState<string | null>(null);

  // Sort: open first, then half_open, then closed
  const sortedBreakers = [...breakers].sort((a, b) => {
    const order = { open: 0, half_open: 1, closed: 2 };
    return order[a.state] - order[b.state];
  });

  const handleReset = async (name: string) => {
    setResettingName(name);
    try {
      await onReset(name);
    } finally {
      setResettingName(null);
    }
  };

  return (
    <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
      {sortedBreakers.map((breaker) => (
        <CircuitCard
          key={breaker.name}
          breaker={breaker}
          onReset={handleReset}
          isResetting={resettingName === breaker.name}
        />
      ))}
    </div>
  );
}
