import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useMemo, useState } from "react";
import {
  addMonths,
  format,
  isSameDay,
  isSameMonth,
  startOfMonth,
  startOfWeek,
  addDays,
} from "date-fns";
import { Bell } from "lucide-react";
import { toast } from "sonner";
import { AppShell } from "@/components/AppShell";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/hooks/useAuth";
import {
  fetchMyAttendance,
  REMINDER_OPTIONS,
  setAttendanceStatus,
  type AttendanceEntry,
} from "@/lib/hotspots";
import { cn } from "@/lib/utils";

export const Route = createFileRoute("/_authenticated/calendar")({
  head: () => ({
    meta: [
      { title: "My calendar — HOTSPOTS" },
      { name: "description", content: "Your personal HOTSPOTS calendar of events you're going to." },
      { property: "og:title", content: "My calendar — HOTSPOTS" },
      { property: "og:description", content: "Events you're going to, with reminders." },
    ],
  }),
  component: CalendarPage,
});

function reminderLabel(minutes: number) {
  return REMINDER_OPTIONS.find((r) => r.minutes === minutes)?.label ?? `${minutes} minutes before`;
}

function AgendaItem({ entry }: { entry: AttendanceEntry }) {
  const date = new Date(entry.event.starts_at);
  return (
    <Link
      to="/events/$slug"
      params={{ slug: entry.event.slug ?? entry.event.id }}
      className="flex gap-4 rounded-2xl border border-border bg-card p-4 hover:border-primary"
    >
      <div className="w-14 shrink-0 text-center">
        <p className="font-display text-xl font-extrabold text-primary">{format(date, "d")}</p>
        <p className="text-[11px] uppercase text-muted-foreground">{format(date, "MMM")}</p>
      </div>
      <div className="min-w-0 flex-1">
        <p className="truncate font-semibold">
          {entry.event.categories?.emoji} {entry.event.title}
        </p>
        <p className="text-xs text-muted-foreground">
          {format(date, "h:mm a")} · {entry.event.cities?.name ?? entry.event.venue}
        </p>
        <p className="mt-1 flex items-center gap-1 text-[11px] text-gold">
          <Bell className="h-3 w-3" /> {reminderLabel(entry.reminder_minutes_before)}
        </p>
      </div>
    </Link>
  );
}

function CalendarPage() {
  const { userId } = useAuth();
  const qc = useQueryClient();
  const [view, setView] = useState<"month" | "week" | "agenda">("agenda");
  const [cursor, setCursor] = useState(startOfMonth(new Date()));

  const { data: entries = [], isLoading } = useQuery({
    queryKey: ["attendance", userId],
    queryFn: () => fetchMyAttendance(userId!),
    enabled: Boolean(userId),
  });

  const now = Date.now();
  const upcoming = entries
    .filter((e) => new Date(e.event.starts_at).getTime() >= now && e.status === "going")
    .sort((a, b) => a.event.starts_at.localeCompare(b.event.starts_at));
  const needsConfirm = entries.filter(
    (e) => new Date(e.event.starts_at).getTime() < now && e.status === "going",
  );

  const monthDays = useMemo(() => {
    const start = startOfWeek(startOfMonth(cursor), { weekStartsOn: 1 });
    return Array.from({ length: 42 }, (_, i) => addDays(start, i));
  }, [cursor]);

  const weekDays = useMemo(() => {
    const start = startOfWeek(new Date(), { weekStartsOn: 1 });
    return Array.from({ length: 7 }, (_, i) => addDays(start, i));
  }, []);

  function eventsOn(day: Date) {
    return entries.filter((e) => isSameDay(new Date(e.event.starts_at), day));
  }

  return (
    <AppShell>
      <div className="space-y-6">
        <div>
          <h1 className="font-display text-2xl font-extrabold">My Calendar</h1>
          <p className="text-sm text-muted-foreground">
            Everything you said you're going to, all in HOTSPOTS.
          </p>
        </div>

        {needsConfirm.length > 0 && (
          <div className="space-y-3 rounded-2xl border border-gold/40 bg-gold/10 p-4">
            <p className="font-semibold">Did you attend these events?</p>
            {needsConfirm.map((e) => (
              <div key={e.event.id} className="flex flex-wrap items-center gap-2">
                <span className="flex-1 text-sm">{e.event.title}</span>
                <Button
                  size="sm"
                  className="rounded-full"
                  onClick={async () => {
                    await setAttendanceStatus(e.event.id, userId!, "attended");
                    toast.success("Marked as attended — you can now rate it");
                    qc.invalidateQueries({ queryKey: ["attendance", userId] });
                  }}
                >
                  Yes, I went
                </Button>
                <Button
                  size="sm"
                  variant="secondary"
                  className="rounded-full"
                  onClick={async () => {
                    await setAttendanceStatus(e.event.id, userId!, "did_not_attend");
                    qc.invalidateQueries({ queryKey: ["attendance", userId] });
                  }}
                >
                  No, I didn't
                </Button>
              </div>
            ))}
          </div>
        )}

        <div className="flex gap-2">
          {(["month", "week", "agenda"] as const).map((v) => (
            <button
              key={v}
              onClick={() => setView(v)}
              className={cn(
                "rounded-full border px-4 py-1.5 text-xs font-medium capitalize",
                view === v ? "border-primary bg-primary/15 text-primary" : "border-border",
              )}
            >
              {v}
            </button>
          ))}
        </div>

        {isLoading ? (
          <div className="h-48 animate-pulse rounded-2xl bg-card" />
        ) : view === "agenda" ? (
          upcoming.length ? (
            <div className="space-y-3">
              {upcoming.map((e) => (
                <AgendaItem key={e.event.id} entry={e} />
              ))}
            </div>
          ) : (
            <EmptyCalendar />
          )
        ) : view === "week" ? (
          <div className="grid gap-3 sm:grid-cols-7">
            {weekDays.map((day) => (
              <div key={day.toISOString()} className="rounded-2xl border border-border bg-card p-3">
                <p className="text-xs font-semibold text-muted-foreground">
                  {format(day, "EEE d")}
                </p>
                <div className="mt-2 space-y-2">
                  {eventsOn(day).map((e) => (
                    <Link
                      key={e.event.id}
                      to="/events/$slug"
                      params={{ slug: e.event.slug ?? e.event.id }}
                      className="block rounded-lg bg-primary/15 p-2 text-[11px] text-primary"
                    >
                      {format(new Date(e.event.starts_at), "h:mm a")} {e.event.title}
                    </Link>
                  ))}
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="rounded-2xl border border-border bg-card p-4">
            <div className="mb-3 flex items-center justify-between">
              <Button variant="ghost" size="sm" onClick={() => setCursor(addMonths(cursor, -1))}>
                ‹
              </Button>
              <p className="font-display font-bold">{format(cursor, "MMMM yyyy")}</p>
              <Button variant="ghost" size="sm" onClick={() => setCursor(addMonths(cursor, 1))}>
                ›
              </Button>
            </div>
            <div className="grid grid-cols-7 gap-1 text-center text-[11px] text-muted-foreground">
              {["M", "T", "W", "T", "F", "S", "S"].map((d, i) => (
                <span key={i}>{d}</span>
              ))}
            </div>
            <div className="mt-1 grid grid-cols-7 gap-1">
              {monthDays.map((day) => {
                const dayEvents = eventsOn(day);
                return (
                  <div
                    key={day.toISOString()}
                    className={cn(
                      "min-h-16 rounded-lg border border-border/50 p-1 text-[11px]",
                      !isSameMonth(day, cursor) && "opacity-40",
                      isSameDay(day, new Date()) && "border-primary",
                    )}
                  >
                    <span>{format(day, "d")}</span>
                    {dayEvents.map((e) => (
                      <Link
                        key={e.event.id}
                        to="/events/$slug"
                        params={{ slug: e.event.slug ?? e.event.id }}
                        className="mt-1 block truncate rounded bg-primary/20 px-1 text-primary"
                      >
                        {e.event.title}
                      </Link>
                    ))}
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </div>
    </AppShell>
  );
}

function EmptyCalendar() {
  return (
    <div className="rounded-2xl border border-border bg-card p-10 text-center">
      <p className="font-display text-lg font-bold">Your calendar is empty</p>
      <p className="mt-1 text-sm text-muted-foreground">
        Tap "I'm Going" on an event and it lands here with a reminder.
      </p>
      <Button asChild className="mt-4 rounded-full">
        <Link to="/discover">Find events</Link>
      </Button>
    </div>
  );
}
