import { useState } from "react";
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { motion } from "motion/react";
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";
import { trpc } from "@/lib/trpc";

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 [projectFilter, setProjectFilter] = useState<string>("all");
  const [createDialogOpen, setCreateDialogOpen] = useState(false);
  const projectsQuery = trpc.listProjects.useQuery();

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

  return (
    <motion.div
      initial={{ opacity: 0, y: 8 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3, ease: [0, 0, 0.2, 1] }}
      className="mx-auto max-w-6xl space-y-6"
    >
      {/* Page header */}
      <div className="flex items-center justify-between">
        <h1 className="font-display text-2xl font-semibold">Initiatives</h1>
        <div className="flex items-center gap-3">
          <select
            value={projectFilter}
            onChange={(e) => setProjectFilter(e.target.value)}
            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"
          >
            <option value="all">All projects</option>
            {(projectsQuery.data ?? []).map((p) => (
              <option key={p.id} value={p.id}>
                {p.name}
              </option>
            ))}
          </select>
          <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 */}
      <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] }}
      >
        <InitiativeList
          statusFilter={statusFilter}
          projectFilter={projectFilter === "all" ? undefined : projectFilter}
          onCreateNew={() => setCreateDialogOpen(true)}
          onViewInitiative={(id) =>
            navigate({ to: "/initiatives/$id", params: { id } })
          }
        />
      </motion.div>

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