import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { AppShell } from "@/components/AppShell";
import { EventCard } from "@/components/EventCard";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/hooks/useAuth";
import { fetchMyAttendance, fetchMyLiked, fetchMySaved, type HotspotEvent } from "@/lib/hotspots";
import { cn } from "@/lib/utils";

export const Route = createFileRoute("/_authenticated/my-events")({
  head: () => ({
    meta: [
      { title: "My events — HOTSPOTS" },
      { name: "description", content: "Events you're going to, attended, saved and liked." },
      { property: "og:title", content: "My events — HOTSPOTS" },
      { property: "og:description", content: "Your personal HOTSPOTS event history." },
    ],
  }),
  component: MyEventsPage,
});

const TABS = ["going", "attended", "missed", "saved", "liked"] as const;
type Tab = (typeof TABS)[number];

function Grid({ events }: { events: HotspotEvent[] }) {
  if (!events.length) {
    return (
      <div className="rounded-2xl border border-border bg-card p-10 text-center">
        <p className="font-display text-lg font-bold">Nothing here yet</p>
        <Button asChild className="mt-4 rounded-full">
          <Link to="/discover">Discover events</Link>
        </Button>
      </div>
    );
  }
  return (
    <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
      {events.map((e) => (
        <EventCard key={e.id} event={e} />
      ))}
    </div>
  );
}

function MyEventsPage() {
  const { userId } = useAuth();
  const [tab, setTab] = useState<Tab>("going");

  const attendance = useQuery({
    queryKey: ["attendance", userId],
    queryFn: () => fetchMyAttendance(userId!),
    enabled: Boolean(userId),
  });
  const saved = useQuery({
    queryKey: ["saved", userId],
    queryFn: () => fetchMySaved(userId!),
    enabled: Boolean(userId),
  });
  const liked = useQuery({
    queryKey: ["liked", userId],
    queryFn: () => fetchMyLiked(userId!),
    enabled: Boolean(userId),
  });

  const rows = attendance.data ?? [];
  const byStatus = (status: string) => rows.filter((r) => r.status === status).map((r) => r.event);

  const content =
    tab === "going"
      ? byStatus("going")
      : tab === "attended"
        ? byStatus("attended")
        : tab === "missed"
          ? byStatus("did_not_attend")
          : tab === "saved"
            ? (saved.data ?? [])
            : (liked.data ?? []);

  return (
    <AppShell>
      <div className="space-y-6">
        <div>
          <h1 className="font-display text-2xl font-extrabold">My Events</h1>
          <p className="text-sm text-muted-foreground">Your event journey on HOTSPOTS.</p>
        </div>
        <div className="hs-scroll-row hide-scrollbar">
          {TABS.map((t) => (
            <button
              key={t}
              onClick={() => setTab(t)}
              className={cn(
                "shrink-0 rounded-full border px-4 py-1.5 text-xs font-medium capitalize",
                tab === t ? "border-primary bg-primary/15 text-primary" : "border-border",
              )}
            >
              {t === "missed" ? "Didn't attend" : t}
            </button>
          ))}
        </div>
        <Grid events={content} />
      </div>
    </AppShell>
  );
}
