import { useMemo } from "react";
import { Loader2, Play } from "lucide-react";
import { StatusDot, mapEntityStatus } from "@/components/StatusDot";
import { trpc } from "@/lib/trpc";
import { cn } from "@/lib/utils";
import { TaskGraph } from "@/components/execution/TaskGraph";
import { useExecutionContext } from "@/components/execution";
import type { SerializedTask } from "@/components/TaskRow";

export interface DetailAgentInfo {
  status: string;
  createdAt: string | Date;
}

interface PipelinePhaseGroupProps {
  phase: {
    id: string;
    name: string;
    status: string;
  };
  tasks: SerializedTask[];
  taskDepsRaw: Array<{ taskId: string; dependsOn: string[] }>;
  isBlocked: boolean;
  detailAgent?: DetailAgentInfo | null;
}

const statusBorderColor: Record<string, string> = {
  active: "border-l-status-active-dot",
  success: "border-l-status-success-dot",
  warning: "border-l-status-warning-dot",
  error: "border-l-status-error-dot",
  neutral: "border-l-border",
  urgent: "border-l-status-urgent-dot",
};

const emptyAgentMap = new Map<string, string>();

export function PipelinePhaseGroup({ phase, tasks, taskDepsRaw, isBlocked, detailAgent }: PipelinePhaseGroupProps) {
  const approvePhase = trpc.approvePhase.useMutation();
  const queuePhase = trpc.queuePhase.useMutation();
  const { setSelectedTaskId } = useExecutionContext();

  // Compute blocked-by counts for TaskGraph
  const blockedByCountMap = useMemo(() => {
    const countMap = new Map<string, number>();
    for (const raw of taskDepsRaw) {
      const incomplete = raw.dependsOn.filter((depId) => {
        const dep = tasks.find((t) => t.id === depId);
        return dep && dep.status !== "completed";
      }).length;
      if (incomplete > 0) countMap.set(raw.taskId, incomplete);
    }
    return countMap;
  }, [tasks, taskDepsRaw]);

  const completedCount = tasks.filter((t) => t.status === "completed").length;
  const totalCount = tasks.length;
  const progressPct = totalCount > 0 ? (completedCount / totalCount) * 100 : 0;

  const hasNonDetailTasks = tasks.length > 0;
  const canExecute =
    (phase.status === "approved" || (phase.status === "pending" && hasNonDetailTasks)) &&
    !isBlocked;
  const isPending = phase.status === "pending";
  const isMutating = approvePhase.isPending || queuePhase.isPending;
  const isDetailing =
    detailAgent?.status === "running" ||
    detailAgent?.status === "waiting_for_input";
  const detailDone = detailAgent?.status === "idle";

  const variant = mapEntityStatus(phase.status);
  const borderClass = statusBorderColor[variant] ?? statusBorderColor.neutral;

  return (
    <div className={cn(
      "rounded-lg border border-border border-l-2 bg-card overflow-hidden",
      borderClass,
    )}>
      {/* Header */}
      <div className="flex items-center gap-2 px-3 py-2 bg-muted/30">
        <StatusDot status={phase.status} size="sm" />
        <span className="min-w-0 flex-1 truncate text-sm font-medium">
          {phase.name}
        </span>
        {totalCount > 0 && (
          <span className="shrink-0 text-[10px] tabular-nums text-muted-foreground">
            {completedCount}/{totalCount}
          </span>
        )}
        {canExecute && (
          <button
            onClick={async () => {
              if (isPending) {
                await approvePhase.mutateAsync({ phaseId: phase.id });
              }
              queuePhase.mutate({ phaseId: phase.id });
            }}
            disabled={isMutating}
            title={isPending ? "Approve & queue phase" : "Queue phase"}
            className="shrink-0"
          >
            {isMutating ? (
              <Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" />
            ) : (
              <Play className="h-3.5 w-3.5 text-muted-foreground hover:text-foreground" />
            )}
          </button>
        )}
      </div>

      {/* Progress bar */}
      {totalCount > 0 && (
        <div className="h-0.5 bg-muted">
          <div
            className={cn(
              "h-full transition-all duration-500 ease-out",
              completedCount === totalCount
                ? "bg-status-success-dot"
                : "bg-status-active-dot",
            )}
            style={{ width: `${progressPct}%` }}
          />
        </div>
      )}

      {/* Tasks */}
      <div className="px-1 py-1">
        {isDetailing ? (
          <p className="flex items-center gap-1.5 px-2 py-1 text-xs text-status-active-fg">
            <Loader2 className="h-3 w-3 animate-spin" />
            Detailing…
          </p>
        ) : detailDone && tasks.length === 0 ? (
          <p className="px-2 py-1 text-xs text-status-warning-fg">Review changes</p>
        ) : tasks.length === 0 ? (
          <p className="px-2 py-1 text-xs text-muted-foreground">No tasks</p>
        ) : (
          <TaskGraph
            tasks={tasks}
            taskDepsRaw={taskDepsRaw}
            blockedByCountMap={blockedByCountMap}
            agentNameMap={emptyAgentMap}
            onClickTask={setSelectedTaskId}
            compact
          />
        )}
      </div>
    </div>
  );
}
