import type { Metadata } from "next";
import Image from "next/image";
import Link from "next/link";
import type { ReactNode } from "react";
import { Heart, History, ListVideo, Settings, Shield } from "lucide-react";

import { requireSession } from "@/lib/require-session";
import { countHistory } from "@/db/queries/progress";
import { countWatchlist, listFavorites } from "@/db/queries/lists";
import { formatDateLong, profileUrl, cn } from "@/lib/utils";

export const metadata: Metadata = {
  title: "Profile",
  description: "Your FlixTV account at a glance.",
  robots: { index: false, follow: false },
};

export const dynamic = "force-dynamic";

/**
 * /profile
 *
 * A dashboard rather than an edit form — editing lives in `/settings`. The
 * counts come straight from the datastore so the page is a true reflection of the
 * account, not a cached number.
 */
export default async function ProfilePage() {
  const session = await requireSession("/profile");
  const user = session.user;

  const [listCount, historyCount, favorites] = await Promise.all([
    countWatchlist(user.id),
    countHistory(user.id),
    listFavorites(user.id, { limit: 200 }),
  ]);
  const favoriteCount = favorites.length;

  const avatar = profileUrl(user.avatarPath);
  const initials = user.displayName.charAt(0).toUpperCase() || user.username.charAt(0).toUpperCase();

  return (
    <main className="pb-24">
      <header className="relative overflow-hidden border-b border-line pb-10 pt-10 md:pt-12">
        <div aria-hidden className="pointer-events-none absolute inset-0 -z-10">
          <div className="absolute -top-40 left-1/4 h-[400px] w-[520px] rounded-full bg-brand-600/18 blur-[130px]" />
        </div>

        <div className="mx-auto w-full max-w-4xl px-4 sm:px-6">
          <div className="flex flex-wrap items-center gap-5">
            <div className="relative size-20 shrink-0 overflow-hidden rounded-full bg-surface-2 ring-1 ring-white/10">
              {avatar ? (
                <Image src={avatar} alt="" fill sizes="80px" className="object-cover" />
              ) : (
                <span className="grid size-full place-items-center text-2xl font-bold text-ink-faint">
                  {initials}
                </span>
              )}
            </div>

            <div className="min-w-0 flex-1">
              <h1 className="font-display text-3xl font-extrabold tracking-[-0.03em] text-balance text-ink">
                {user.displayName}
              </h1>
              <p className="mt-1 text-[13px] text-ink-muted">
                @{user.username} · {user.email}
              </p>
              <p className="mt-0.5 text-[12px] text-ink-faint">
                Member since {formatDateLong(user.createdAt)}
              </p>
            </div>

            <Link
              href="/settings"
              className="inline-flex h-10 items-center gap-2 rounded-pill border border-line px-4 text-[13px] font-semibold text-ink-soft transition-colors hover:border-white/30 hover:text-ink"
            >
              <Settings className="size-3.5" />
              Settings
            </Link>
          </div>
        </div>
      </header>

      <div className="mx-auto w-full max-w-4xl px-4 py-9 sm:px-6">
        <ul className="grid grid-cols-3 gap-3">
          <Stat href="/my-list?tab=watchlist" label="Watchlist" value={listCount} icon={<ListVideo className="size-4" />} />
          <Stat href="/my-list?tab=favorites" label="Favourites" value={favoriteCount} icon={<Heart className="size-4" />} />
          <Stat href="/history" label="Watched" value={historyCount} icon={<History className="size-4" />} />
        </ul>

        <section className="mt-8 rounded-xl border border-line bg-surface-2/40 p-5 sm:p-6">
          <h2 className="flex items-center gap-2.5 font-display text-base font-bold text-ink">
            <Shield className="size-4 text-brand-400" />
            Account details
          </h2>
          <dl className="mt-4 divide-y divide-line">
            <Row label="Username" value={user.username} />
            <Row label="Display name" value={user.displayName} />
            <Row label="Email" value={user.email} />
            <Row label="Account type" value={user.role === "user" ? "Standard" : user.role} />
            <Row label="Session expires" value={formatDateLong(session.expiresAt)} />
          </dl>
        </section>

        {favorites.length > 0 ? (
          <section className="mt-8">
            <h2 className="mb-4 flex items-center gap-3 font-display text-lg font-bold tracking-[-0.02em] text-ink">
              <span aria-hidden className="row-tick" />
              Recent favourites
            </h2>
            <ul className="grid grid-cols-4 gap-3 sm:grid-cols-6">
              {favorites.slice(0, 6).map((item) => (
                <li key={`${item.mediaType}-${item.id}`} className="min-w-0">
                  <Link
                    href={item.mediaType === "movie" ? `/movie/${item.id}` : `/tv/${item.id}`}
                    className="group block"
                  >
                    <div className="relative aspect-2/3 overflow-hidden rounded-md bg-surface-2 ring-1 ring-white/5 transition-all duration-300 group-hover:ring-white/25">
                      {item.posterPath ? (
                        <Image
                          src={`https://image.tmdb.org/t/p/w342${item.posterPath}`}
                          alt=""
                          fill
                          sizes="150px"
                          className="object-cover transition-transform duration-500 group-hover:scale-105"
                        />
                      ) : null}
                    </div>
                    <p className="mt-2 line-clamp-2x text-[12px] font-semibold leading-tight text-ink">
                      {item.title}
                    </p>
                  </Link>
                </li>
              ))}
            </ul>
          </section>
        ) : null}
      </div>
    </main>
  );
}

function Stat({
  href,
  label,
  value,
  icon,
}: {
  href: string;
  label: string;
  value: number;
  icon: ReactNode;
}) {
  return (
    <li>
      <Link
        href={href}
        className="group flex flex-col items-center gap-1.5 rounded-xl border border-line bg-surface-2/40 p-4 transition-colors hover:border-white/25 hover:bg-surface-3/50"
      >
        <span className="text-ink-faint transition-colors group-hover:text-brand-400">{icon}</span>
        <span className="font-display text-2xl font-extrabold tabular-nums text-ink">{value}</span>
        <span className="text-[12px] font-medium text-ink-muted">{label}</span>
      </Link>
    </li>
  );
}

function Row({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-baseline justify-between gap-4 py-2.5">
      <dt className="text-[13px] text-ink-faint">{label}</dt>
      <dd className={cn("min-w-0 truncate text-right text-[13px] font-semibold text-ink")}>
        {value}
      </dd>
    </div>
  );
}
