import { useState } from "react";
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { Plus } from "lucide-react";
import { Button } from "@/components/ui/button";
import { InitiativeList } from "@/components/InitiativeList";
import { CreateInitiativeDialog } from "@/components/CreateInitiativeDialog";
import { useLiveUpdates } from "@/hooks";

export const Route = createFileRoute("/initiatives/")({
  component: DashboardPage,
});

type StatusFilter = "all" | "active" | "completed" | "archived";

const filterOptions: { value: StatusFilter; label: string }[] = [
  { value: "all", label: "All" },
  { value: "active", label: "Active" },
  { value: "completed", label: "Completed" },
  { value: "archived", label: "Archived" },
];

function DashboardPage() {
  const navigate = useNavigate();
  const [statusFilter, setStatusFilter] = useState<StatusFilter>("all");
  const [createDialogOpen, setCreateDialogOpen] = useState(false);

  // Single SSE stream for live updates
  useLiveUpdates([
    { prefix: 'task:',  invalidate: ['listInitiatives', 'listPhases'] },
    { prefix: 'phase:', invalidate: ['listInitiatives', 'listPhases'] },
  ]);

  return (
    <div className="space-y-6">
      {/* Page header */}
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">Initiatives</h1>
        <div className="flex items-center gap-3">
          <select
            value={statusFilter}
            onChange={(e) =>
              setStatusFilter(e.target.value as StatusFilter)
            }
            className="rounded-md border border-input bg-background px-3 py-1.5 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
          >
            {filterOptions.map((opt) => (
              <option key={opt.value} value={opt.value}>
                {opt.label}
              </option>
            ))}
          </select>
          <Button size="sm" onClick={() => setCreateDialogOpen(true)}>
            <Plus className="mr-1 h-4 w-4" />
            New Initiative
          </Button>
        </div>
      </div>

      {/* Initiative list */}
      <InitiativeList
        statusFilter={statusFilter}
        onCreateNew={() => setCreateDialogOpen(true)}
        onViewInitiative={(id) =>
          navigate({ to: "/initiatives/$id", params: { id } })
        }
        onSpawnArchitect={(_initiativeId, _mode) => {
          // Architect spawning is self-contained within SpawnArchitectDropdown
          // This callback is available for future toast notifications
        }}
        onDeleteInitiative={(_id) => {
          // Delete is a placeholder (no deleteInitiative tRPC procedure yet)
          // ActionMenu handles this internally when implemented
        }}
      />

      {/* Create initiative dialog */}
      <CreateInitiativeDialog
        open={createDialogOpen}
        onOpenChange={setCreateDialogOpen}
      />
    </div>
  );
}
