import { Play } from "lucide-react";
import { StatusDot } from "@/components/StatusDot";
import { trpc } from "@/lib/trpc";
import { sortByPriorityAndQueueTime } from "@codewalk-district/shared";
import { PipelineTaskCard } from "./PipelineTaskCard";
import type { SerializedTask } from "@/components/TaskRow";

interface PipelinePhaseGroupProps {
  phase: {
    id: string;
    name: string;
    status: string;
  };
  tasks: SerializedTask[];
}

export function PipelinePhaseGroup({ phase, tasks }: PipelinePhaseGroupProps) {
  const queuePhase = trpc.queuePhase.useMutation();
  const sorted = sortByPriorityAndQueueTime(tasks);

  return (
    <div className="rounded-lg border border-border bg-card overflow-hidden">
      {/* Header */}
      <div className="flex items-center gap-2 px-3 py-2 border-b border-border bg-muted/30">
        <StatusDot status={phase.status} size="sm" />
        <span className="min-w-0 flex-1 truncate text-sm font-medium">
          {phase.name}
        </span>
        {phase.status === "pending" && (
          <button
            onClick={() => queuePhase.mutate({ phaseId: phase.id })}
            title="Queue phase"
            className="shrink-0"
          >
            <Play className="h-3.5 w-3.5 text-muted-foreground hover:text-foreground" />
          </button>
        )}
      </div>

      {/* Tasks */}
      <div className="py-1">
        {sorted.length === 0 ? (
          <p className="px-3 py-1 text-xs text-muted-foreground">No tasks</p>
        ) : (
          sorted.map((task) => (
            <PipelineTaskCard key={task.id} task={task} />
          ))
        )}
      </div>
    </div>
  );
}
