import { createFileRoute } from "@tanstack/react-router";
import { pb } from "@/lib/pocketbase";
import type { Campaign } from "@/lib/types";
import { Link } from "@tanstack/react-router";
import { Loader } from "@/components/Loader";
import { CreateCampaignButton } from "@/components/CreateCampaignButton";
import { useRouter } from "@tanstack/react-router";

export const Route = createFileRoute("/_authenticated/campaigns/")({
  loader: async () => {
    const records = await pb.collection("campaigns").getFullList();
    return {
      campaigns: records.map((rec: any) => ({
        id: rec.id,
        name: rec.name,
      })) as Campaign[],
    };
  },
  component: RouteComponent,
  pendingComponent: Loader,
});

function RouteComponent() {
  const { campaigns } = Route.useLoaderData();
  const router = useRouter();

  const handleCreated = async () => {
    await router.invalidate();
  };

  return (
    <div className="max-w-xl mx-auto py-8">
      <h2 className="text-xl font-bold mb-4 text-slate-100">Your Campaigns</h2>
      {!campaigns || campaigns.length === 0 ? (
        <div>No campaigns found.</div>
      ) : (
        <ul className="space-y-2">
          {campaigns.map((c) => (
            <li key={c.id}>
              <Link
                to="/campaigns/$campaignId"
                params={{ campaignId: c.id }}
                className="block px-4 py-2 rounded bg-slate-800 hover:bg-violet-700 text-slate-100 transition-colors"
              >
                {c.name}
              </Link>
            </li>
          ))}
        </ul>
      )}
      <div className="mt-8">
        <CreateCampaignButton onCreated={handleCreated} />
      </div>
    </div>
  );
}
