import { MoreHorizontal } from "lucide-react";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { StatusDot, type StatusVariant } from "@/components/StatusDot";
import { trpc } from "@/lib/trpc";

/** Initiative shape as returned by tRPC (Date serialized to string over JSON) */
export interface SerializedInitiative {
  id: string;
  name: string;
  status: "active" | "completed" | "archived";
  branch: string | null;
  createdAt: string;
  updatedAt: string;
  projects?: Array<{ id: string; name: string }>;
  activity: {
    state: string;
    activePhase?: { id: string; name: string } | null;
    phasesTotal: number;
    phasesCompleted: number;
  };
}

function activityVisual(state: string): { label: string; variant: StatusVariant; pulse: boolean } {
  switch (state) {
    case "executing":          return { label: "Executing",          variant: "active",  pulse: true };
    case "pending_review":     return { label: "Pending Review",     variant: "warning", pulse: true };
    case "discussing":         return { label: "Discussing",         variant: "active",  pulse: true };
    case "detailing":          return { label: "Detailing",          variant: "active",  pulse: true };
    case "refining":           return { label: "Refining",           variant: "active",  pulse: true };
    case "resolving_conflict": return { label: "Resolving Conflict", variant: "urgent",  pulse: true };
    case "ready":          return { label: "Ready",           variant: "active",  pulse: false };
    case "blocked":        return { label: "Blocked",         variant: "error",   pulse: false };
    case "complete":       return { label: "Complete",        variant: "success", pulse: false };
    case "planning":       return { label: "Planning",        variant: "neutral", pulse: false };
    case "archived":       return { label: "Archived",        variant: "neutral", pulse: false };
    default:               return { label: "Idle",            variant: "neutral", pulse: false };
  }
}

interface InitiativeCardProps {
  initiative: SerializedInitiative;
  onClick: () => void;
}

export function InitiativeCard({ initiative, onClick }: InitiativeCardProps) {
  const utils = trpc.useUtils();
  const archiveMutation = trpc.updateInitiative.useMutation({
    onSuccess: () => utils.listInitiatives.invalidate(),
  });
  const deleteMutation = trpc.deleteInitiative.useMutation({
    onSuccess: () => utils.listInitiatives.invalidate(),
  });

  function handleArchive(e: React.MouseEvent) {
    if (
      !e.shiftKey &&
      !window.confirm(`Archive "${initiative.name}"?`)
    ) {
      return;
    }
    archiveMutation.mutate({ id: initiative.id, status: "archived" });
  }

  function handleDelete(e: React.MouseEvent) {
    if (
      !e.shiftKey &&
      !window.confirm(`Delete "${initiative.name}"? This cannot be undone.`)
    ) {
      return;
    }
    deleteMutation.mutate({ id: initiative.id });
  }

  const { activity } = initiative;
  const visual = activityVisual(activity.state);
  const projects = initiative.projects ?? [];

  return (
    <Card
      interactive
      className="px-4 py-2 group"
      onClick={onClick}
    >
      <div className="flex items-center gap-2 min-w-0">
        <StatusDot
          status={activity.state}
          variant={visual.variant}
          size="sm"
          pulse={visual.pulse}
        />

        <span className="truncate min-w-0 flex-1 font-semibold text-sm">
          {initiative.name}
        </span>

        {activity.activePhase && (
          <>
            <span className="text-muted-foreground text-sm shrink-0">·</span>
            <span className="truncate text-sm text-muted-foreground">
              {activity.activePhase.name}
            </span>
          </>
        )}

        {activity.phasesTotal > 0 && (
          <span className="ml-auto text-xs text-muted-foreground whitespace-nowrap shrink-0">
            {activity.phasesCompleted} / {activity.phasesTotal}
          </span>
        )}

        {projects.slice(0, 2).map((p) => (
          <Badge key={p.id} variant="outline" size="xs" className="shrink-0">
            {p.name}
          </Badge>
        ))}
        {projects.length > 2 && (
          <Badge variant="secondary" size="xs" className="shrink-0">
            +{projects.length - 2}
          </Badge>
        )}

        <div
          className="shrink-0 opacity-0 group-hover:opacity-100 transition-opacity"
          onClick={(e) => e.stopPropagation()}
        >
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="ghost" size="icon" className="h-7 w-7">
                <MoreHorizontal className="h-4 w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem onClick={handleArchive}>Archive</DropdownMenuItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem
                className="text-destructive"
                onClick={handleDelete}
              >
                Delete
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>
    </Card>
  );
}
