import { Card, StatusDot } from "@cv/ui";
import type { QueueStatsQuery } from "@/generated/graphql";

type Stats = NonNullable<QueueStatsQuery["queueStats"]>;

const formatDuration = (seconds: number): string => {
  if (seconds < 60) return `${Math.round(seconds)}s`;
  const minutes = Math.floor(seconds / 60);
  if (minutes < 60) return `${minutes}m ${Math.round(seconds % 60)}s`;
  const hours = Math.floor(minutes / 60);
  return `${hours}h ${minutes % 60}m`;
};

const DetailRow = ({
  label,
  value,
}: {
  label: string;
  value: React.ReactNode;
}) => (
  <div className="flex justify-between py-1.5 border-b border-ctp-surface1 last:border-b-0">
    <span className="text-sm text-ctp-subtext0">{label}</span>
    <span className="text-sm font-medium text-ctp-text">{value}</span>
  </div>
);

interface QueueStatsCardProps {
  stats: Stats;
}

export const QueueStatsCard = ({ stats }: QueueStatsCardProps) => (
  <Card>
    <h3 className="mb-3 text-lg font-medium text-ctp-text">Queue</h3>
    <div className="space-y-0">
      <DetailRow
        label="Pending"
        value={
          <span className="flex items-center gap-2">
            <StatusDot color={stats.pending === 0 ? "green" : "yellow"} />
            {stats.pending}
          </span>
        }
      />
      <DetailRow label="Scheduled" value={stats.scheduled} />
      <DetailRow label="Processing" value={stats.processing} />
      <DetailRow
        label="Oldest Pending"
        value={
          stats.oldestPendingSeconds != null
            ? formatDuration(stats.oldestPendingSeconds)
            : "none"
        }
      />
    </div>
  </Card>
);
