import { ArrowUp, Loader2 } from "lucide-react";
import { StatusBadge } from "@/components/StatusBadge";
import { PhaseNumberBadge } from "@/components/DependencyChip";
import { cn } from "@/lib/utils";

export interface PhaseDependencyInfo {
  displayIndex: number;
  status: string;
}

interface PhaseSidebarItemProps {
  phase: {
    id: string;
    name: string;
    status: string;
  };
  displayIndex: number;
  taskCount: { complete: number; total: number };
  dependencies: PhaseDependencyInfo[];
  isSelected: boolean;
  onClick: () => void;
  detailAgent?: { status: string } | null;
}

export function PhaseSidebarItem({
  phase,
  displayIndex,
  taskCount,
  dependencies,
  isSelected,
  onClick,
  detailAgent,
}: PhaseSidebarItemProps) {
  const isDetailing =
    detailAgent?.status === "running" ||
    detailAgent?.status === "waiting_for_input";
  const detailDone = detailAgent?.status === "idle";

  function renderTaskStatus() {
    if (isDetailing) {
      return (
        <span className="flex items-center gap-1 text-status-active-fg">
          <Loader2 className="h-3 w-3 animate-spin" />
          Detailing…
        </span>
      );
    }
    if (detailDone && taskCount.total === 0) {
      return <span className="text-status-warning-fg">Review changes</span>;
    }
    if (taskCount.total === 0) {
      return <span>Needs decomposition</span>;
    }
    return (
      <span>
        {taskCount.complete}/{taskCount.total} tasks
      </span>
    );
  }

  const sortedDeps = [...dependencies].sort(
    (a, b) => a.displayIndex - b.displayIndex,
  );

  return (
    <button
      className={cn(
        "flex w-full flex-col gap-0.5 rounded-md px-3 py-2 text-left transition-colors",
        isSelected
          ? "border-l-2 border-primary bg-accent"
          : "border-l-2 border-transparent hover:bg-accent/50",
      )}
      onClick={onClick}
    >
      <div className="flex items-center gap-2">
        <span className="min-w-0 flex-1 truncate text-sm font-medium">
          Phase {displayIndex}: {phase.name}
        </span>
        <StatusBadge status={phase.status} className="shrink-0 text-[10px]" />
      </div>

      <div className="flex items-center gap-2 text-xs text-muted-foreground">
        {renderTaskStatus()}
      </div>

      {sortedDeps.length > 0 && (
        <div className="flex items-center gap-1 pt-0.5">
          <ArrowUp className="h-3 w-3 shrink-0 text-muted-foreground/50" />
          <div className="flex flex-wrap gap-0.5">
            {sortedDeps.map((dep) => (
              <PhaseNumberBadge
                key={dep.displayIndex}
                index={dep.displayIndex}
                status={dep.status}
              />
            ))}
          </div>
        </div>
      )}
    </button>
  );
}
