import { Link } from "@tanstack/react-router";
import { StatusBadge } from "@/components/StatusBadge";
import { DependencyIndicator } from "@/components/DependencyIndicator";
import { cn } from "@/lib/utils";

/** Task shape as returned by tRPC (Date fields serialized to string over JSON) */
export interface SerializedTask {
  id: string;
  phaseId: string | null;
  initiativeId: string | null;
  parentTaskId: string | null;
  name: string;
  description: string | null;
  type: "auto" | "checkpoint:human-verify" | "checkpoint:decision" | "checkpoint:human-action";
  category: string;
  priority: "low" | "medium" | "high";
  status: "pending_approval" | "pending" | "in_progress" | "completed" | "blocked";
  requiresApproval: boolean | null;
  order: number;
  createdAt: string;
  updatedAt: string;
}

interface TaskRowProps {
  task: SerializedTask;
  agentName: string | null;
  blockedBy: Array<{ name: string; status: string }>;
  isLast: boolean;
  onClick: () => void;
}

export function TaskRow({
  task,
  agentName,
  blockedBy,
  isLast,
  onClick,
}: TaskRowProps) {
  const connector = isLast ? "└──" : "├──";

  return (
    <div>
      {/* Task row */}
      <div
        className={cn(
          "flex cursor-pointer items-center gap-2 rounded px-2 py-1 hover:bg-accent",
          !isLast && "border-l-2 border-muted-foreground/20",
        )}
        onClick={onClick}
      >
        {/* Tree connector */}
        <span className="shrink-0 font-mono text-sm text-muted-foreground">
          {connector}
        </span>

        {/* Task name */}
        <span className="min-w-0 flex-1 truncate text-sm">{task.name}</span>

        {/* Agent assignment */}
        {agentName && (
          <Link
            to="/inbox"
            className="shrink-0 text-xs text-primary hover:underline"
            onClick={(e) => e.stopPropagation()}
          >
            [{agentName}]
          </Link>
        )}

        {/* Status badge */}
        <StatusBadge status={task.status} className="shrink-0" />
      </div>

      {/* Dependency indicator below the row */}
      {blockedBy.length > 0 && (
        <DependencyIndicator
          blockedBy={blockedBy}
          type="task"
          className="ml-6"
        />
      )}
    </div>
  );
}
