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

type Worker = WorkerHealthQuery["workerHealth"][number];

type DotColor = "green" | "yellow" | "red";

const statusColor: Record<string, DotColor> = {
  healthy: "green",
  stale: "yellow",
  dead: "red",
};

const formatRelativeTime = (isoString: string): string => {
  const diff = Date.now() - new Date(isoString).getTime();
  const seconds = Math.floor(diff / 1000);

  if (seconds < 60) return `${seconds}s ago`;
  const minutes = Math.floor(seconds / 60);
  if (minutes < 60) return `${minutes}m ago`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours}h ago`;
  return `${Math.floor(hours / 24)}d ago`;
};

const truncateUuid = (uuid: string): string => uuid.slice(0, 8);

interface WorkerHealthCardProps {
  workers: Worker[];
}

export const WorkerHealthCard = ({ workers }: WorkerHealthCardProps) => (
  <Card>
    <h3 className="mb-3 text-lg font-medium text-ctp-text">Workers</h3>
    {workers.length === 0 ? (
      <p className="text-sm text-ctp-subtext0">No workers registered</p>
    ) : (
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-ctp-surface1 text-left text-ctp-subtext0">
              <th className="pb-2 pr-4">Worker ID</th>
              <th className="pb-2 pr-4">Status</th>
              <th className="pb-2 pr-4">Started</th>
              <th className="pb-2 pr-4">Last Seen</th>
            </tr>
          </thead>
          <tbody>
            {workers.map((w) => (
              <tr
                key={w.workerId}
                className="border-b border-ctp-surface1 last:border-b-0"
              >
                <td
                  className="py-1.5 pr-4 font-mono text-xs text-ctp-text"
                  title={w.workerId}
                >
                  {truncateUuid(w.workerId)}
                </td>
                <td className="py-1.5 pr-4">
                  <span className="flex items-center gap-2">
                    <StatusDot color={statusColor[w.status] ?? "gray"} />
                    {w.status}
                  </span>
                </td>
                <td className="py-1.5 pr-4 text-ctp-subtext0">
                  {formatRelativeTime(w.startedAt)}
                </td>
                <td className="py-1.5 pr-4 text-ctp-subtext0">
                  {formatRelativeTime(w.lastSeenAt)}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    )}
  </Card>
);
