import type { Metadata } from "next";
import Link from "next/link";
import type { ReactNode } from "react";
import { Heart, ListVideo } from "lucide-react";

import { PosterCard } from "@/components/media/poster-card";
import { requireSession } from "@/lib/require-session";
import { listFavorites, listWatchlist, type ListItem } from "@/db/queries/lists";
import { cn } from "@/lib/utils";

export const metadata: Metadata = {
  title: "My List",
  description: "Everything you have saved to watch on FlixTV.",
  robots: { index: false, follow: false },
};

type Tab = "watchlist" | "favorites";

/**
 * /my-list
 *
 * Server-rendered from the datastore on every request. The tab is a real link with a
 * `?tab=` parameter rather than client state, so switching tabs is a normal
 * navigation that works without JavaScript and is linkable.
 */
export default async function MyListPage({
  searchParams,
}: {
  searchParams: Promise<{ tab?: string; sort?: string }>;
}) {
  const session = await requireSession("/my-list");
  const { tab: tabParam, sort } = await searchParams;

  const tab: Tab = tabParam === "favorites" ? "favorites" : "watchlist";
  const order = sort === "title" ? "title" : sort === "manual" ? "manual" : "recent";

  // `favorites` has no manual position column, so it only honours the title
  // ordering; everything else falls back to most-recent.
  const items: ListItem[] =
    tab === "favorites"
      ? await listFavorites(session.user.id)
      : await listWatchlist(session.user.id, { order });

  const sorted =
    tab === "favorites" && order === "title"
      ? [...items].sort((a, b) => a.title.localeCompare(b.title))
      : items;

  return (
    <main className="pb-24">
      <header className="border-b border-line pb-8 pt-8 md:pt-10">
        <div className="mx-auto w-full max-w-[1600px] px-4 sm:px-6 lg:px-10">
          <h1 className="font-display text-3xl font-extrabold tracking-[-0.03em] text-ink md:text-4xl">
            My List
          </h1>
          <p className="mt-2.5 text-[15px] text-ink-muted">
            {items.length === 0
              ? "Nothing saved yet."
              : `${items.length} ${items.length === 1 ? "title" : "titles"} saved to your account.`}
          </p>

          <div className="mt-6 flex flex-wrap items-center gap-3">
            <TabLink href="/my-list?tab=watchlist" active={tab === "watchlist"} icon={<ListVideo className="size-3.5" />}>
              Watchlist
            </TabLink>
            <TabLink href="/my-list?tab=favorites" active={tab === "favorites"} icon={<Heart className="size-3.5" />}>
              Favourites
            </TabLink>

            <div className="ml-auto flex items-center gap-1.5">
              <SortLink href={`/my-list?tab=${tab}&sort=recent`} active={order === "recent"}>
                Recent
              </SortLink>
              <SortLink href={`/my-list?tab=${tab}&sort=title`} active={order === "title"}>
                A–Z
              </SortLink>
              {tab === "watchlist" ? (
                <SortLink href={`/my-list?tab=${tab}&sort=manual`} active={order === "manual"}>
                  Manual
                </SortLink>
              ) : null}
            </div>
          </div>
        </div>
      </header>

      <div className="mx-auto w-full max-w-[1600px] px-4 py-9 sm:px-6 lg:px-10">
        {sorted.length === 0 ? (
          <EmptyState tab={tab} />
        ) : (
          <ul className="grid grid-cols-3 gap-x-3 gap-y-7 sm:grid-cols-4 sm:gap-x-4 md:grid-cols-5 lg:grid-cols-6 xl:grid-cols-7 2xl:grid-cols-8">
            {sorted.map((item, index) => (
              <li key={`${item.mediaType}-${item.id}`} className="min-w-0">
                <PosterCard item={item} index={index} className="w-full" />
              </li>
            ))}
          </ul>
        )}
      </div>
    </main>
  );
}

function TabLink({
  href,
  active,
  icon,
  children,
}: {
  href: string;
  active: boolean;
  icon: ReactNode;
  children: ReactNode;
}) {
  return (
    <Link
      href={href}
      aria-current={active ? "page" : undefined}
      className={cn(
        "inline-flex h-9 items-center gap-1.5 rounded-pill px-4 text-[13px] font-semibold transition-colors",
        active
          ? "bg-white text-black"
          : "border border-line text-ink-soft hover:border-white/30 hover:text-ink",
      )}
    >
      {icon}
      {children}
    </Link>
  );
}

function SortLink({
  href,
  active,
  children,
}: {
  href: string;
  active: boolean;
  children: ReactNode;
}) {
  return (
    <Link
      href={href}
      className={cn(
        "rounded-pill px-2.5 py-1 text-[12px] font-semibold transition-colors",
        active ? "text-ink" : "text-ink-faint hover:text-ink-soft",
      )}
    >
      {children}
    </Link>
  );
}

function EmptyState({ tab }: { tab: Tab }) {
  return (
    <div className="rounded-xl border border-dashed border-line-strong bg-surface-2/40 px-6 py-20 text-center">
      {tab === "favorites" ? (
        <Heart className="mx-auto size-7 text-ink-faint" />
      ) : (
        <ListVideo className="mx-auto size-7 text-ink-faint" />
      )}
      <p className="mt-4 text-sm font-semibold text-ink">
        {tab === "favorites" ? "No favourites yet" : "Your list is empty"}
      </p>
      <p className="mx-auto mt-2 max-w-sm text-[13px] leading-relaxed text-ink-muted">
        {tab === "favorites"
          ? "Tap the heart on any title to keep it here for quick access."
          : "Use the + button on any poster to save it for later — it syncs to every device you sign in on."}
      </p>
      <Link
        href="/movies"
        className="mt-6 inline-flex h-10 items-center rounded-pill bg-white px-5 text-sm font-semibold text-black transition-colors hover:bg-white/90"
      >
        Browse movies
      </Link>
    </div>
  );
}
