import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { motion } from "motion/react";
import { AlertCircle } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/Skeleton";
import { trpc } from "@/lib/trpc";
import { cn } from "@/lib/utils";
import { InitiativeHeader } from "@/components/InitiativeHeader";
import { ContentTab } from "@/components/editor/ContentTab";
import { ExecutionTab } from "@/components/ExecutionTab";
import { ReviewTab } from "@/components/review";
import { PipelineTab } from "@/components/pipeline";
import { useLiveUpdates } from "@/hooks";

type Tab = "content" | "plan" | "execution" | "review";
const TABS: Tab[] = ["content", "plan", "execution", "review"];

export const Route = createFileRoute("/initiatives/$id")({
  component: InitiativeDetailPage,
  validateSearch: (search: Record<string, unknown>): { tab: Tab } => ({
    tab: TABS.includes(search.tab as Tab) ? (search.tab as Tab) : "content",
  }),
});

function InitiativeDetailPage() {
  const { id } = Route.useParams();
  const { tab: activeTab } = Route.useSearch();
  const navigate = useNavigate();

  // Single SSE stream for all live updates
  useLiveUpdates([
    { prefix: 'task:',      invalidate: ['listPhases', 'listTasks', 'listInitiativeTasks', 'getPhaseDependencies', 'listPhaseTaskDependencies'] },
    { prefix: 'phase:',     invalidate: ['listPhases', 'listTasks', 'listInitiativePhaseDependencies', 'getPhaseDependencies'] },
    { prefix: 'agent:',     invalidate: ['listAgents', 'getActiveRefineAgent'] },
    { prefix: 'page:',      invalidate: ['listPages', 'getPage', 'getRootPage'] },
    { prefix: 'changeset:', invalidate: ['getChangeSet', 'listChangeSets'] },
    { prefix: 'preview:',   invalidate: ['listPreviews', 'getPreviewStatus'] },
  ]);

  // tRPC queries
  const initiativeQuery = trpc.getInitiative.useQuery({ id });
  const phasesQuery = trpc.listPhases.useQuery({ initiativeId: id });
  const depsQuery = trpc.listInitiativePhaseDependencies.useQuery({ initiativeId: id });

  // Loading state
  if (initiativeQuery.isLoading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center gap-4">
          <Skeleton className="h-4 w-4" />
          <Skeleton className="h-7 w-64" />
          <Skeleton className="h-5 w-20" />
        </div>
        <div className="grid grid-cols-1 gap-6 lg:grid-cols-[1fr_340px]">
          <div className="space-y-1">
            <Skeleton className="h-12 w-full rounded border" />
            <Skeleton className="h-12 w-full rounded border" />
          </div>
          <div className="space-y-6">
            <Skeleton className="h-24 w-full rounded" />
            <Skeleton className="h-20 w-full rounded" />
          </div>
        </div>
      </div>
    );
  }

  // Error state
  if (initiativeQuery.isError) {
    return (
      <div className="flex flex-col items-center justify-center gap-4 py-12">
        <AlertCircle className="h-8 w-8 text-destructive" />
        <p className="text-sm text-destructive">
          {initiativeQuery.error.message.includes("not found")
            ? "Initiative not found"
            : `Failed to load initiative: ${initiativeQuery.error.message}`}
        </p>
        <Button
          variant="outline"
          size="sm"
          onClick={() => navigate({ to: "/initiatives" })}
        >
          Back to Dashboard
        </Button>
      </div>
    );
  }

  const initiative = initiativeQuery.data;
  if (!initiative) return null;

  const serializedInitiative = {
    id: initiative.id,
    name: initiative.name,
    status: initiative.status,
    executionMode: (initiative as any).executionMode as string | undefined,
    branch: (initiative as any).branch as string | null | undefined,
    branchLocked: (initiative as any).branchLocked as boolean | undefined,
  };

  const projects = (initiative as { projects?: Array<{ id: string; name: string; url: string }> }).projects;

  const phases = phasesQuery.data ?? [];

  return (
    <motion.div
      initial={{ opacity: 0, y: 8 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3, ease: [0, 0, 0.2, 1] }}
      className="space-y-3"
    >
      {/* Header */}
      <InitiativeHeader
        initiative={serializedInitiative}
        projects={projects}
        onBack={() => navigate({ to: "/initiatives" })}
      />

      {/* Tab bar */}
      <motion.nav
        initial={{ opacity: 0, y: 8 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.3, delay: 0.05, ease: [0, 0, 0.2, 1] }}
        className="flex gap-1 border-b border-border"
      >
        {TABS.map((tab) => (
          <button
            key={tab}
            onClick={() =>
              navigate({
                search: { tab },
                replace: true,
              })
            }
            className={cn(
              "px-4 py-2 text-sm font-medium border-b-2 transition-colors",
              activeTab === tab
                ? "border-primary text-foreground"
                : "border-transparent text-muted-foreground hover:text-foreground"
            )}
          >
            {tab.charAt(0).toUpperCase() + tab.slice(1)}
          </button>
        ))}
      </motion.nav>

      {/* Tab content */}
      <motion.div
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.3, delay: 0.1, ease: [0, 0, 0.2, 1] }}
      >
        {activeTab === "content" && <ContentTab initiativeId={id} initiativeName={initiative.name} />}
        {activeTab === "plan" && (
          <ExecutionTab
            initiativeId={id}
            phases={phases}
            phasesLoading={phasesQuery.isLoading}
            phasesLoaded={phasesQuery.isSuccess}
            dependencyEdges={depsQuery.data ?? []}
            branch={serializedInitiative.branch}
          />
        )}
        {activeTab === "execution" && (
          <PipelineTab
            initiativeId={id}
            phases={phases}
            phasesLoading={phasesQuery.isLoading}
          />
        )}
        {activeTab === "review" && <ReviewTab initiativeId={id} />}
      </motion.div>
    </motion.div>
  );
}
