import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { redirect } from "next/navigation";
import Link from "next/link";
import { History, ArrowLeft, Trash2 } from "lucide-react";
import { VideoCard } from "@/components/VideoCard";
import { formatNumber, formatDate } from "@/lib/utils";

export const metadata = { title: "Historique | MTBR" };

export default async function HistoryPage() {
  const session = await auth();
  if (!session?.user) redirect("/login");

  const userId = (session.user as any).id;

  const history = await prisma.watchHistory.findMany({
    where: { userId },
    orderBy: { updatedAt: "desc" },
    include: {
      media: {
        include: { category: true },
      },
    },
    take: 100,
  });

  const entries = history.filter((h) => h.media.isPublished);

  // Group by date
  const groupedByDate: Record<string, typeof entries> = {};
  for (const entry of entries) {
    const label = formatDate(entry.updatedAt);
    if (!groupedByDate[label]) groupedByDate[label] = [];
    groupedByDate[label].push(entry);
  }

  return (
    <div className="min-h-screen py-8 px-4">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="flex items-center gap-4 mb-2">
          <Link
            href="/"
            className="w-9 h-9 rounded-full glass flex items-center justify-center hover:border-[var(--accent)] transition-colors border border-transparent"
          >
            <ArrowLeft size={16} />
          </Link>
          <div className="flex-1">
            <h1 className="text-3xl font-black flex items-center gap-3">
              <History size={28} className="text-[var(--accent)]" />
              Historique
            </h1>
            <p className="text-[var(--text-secondary)] text-sm mt-0.5">
              {formatNumber(entries.length)} vidéo{entries.length > 1 ? "s" : ""} regardée{entries.length > 1 ? "s" : ""}
            </p>
          </div>
        </div>

        {/* Divider */}
        <div className="h-px bg-gradient-to-r from-[var(--accent)]/40 via-[var(--border)] to-transparent my-6" />

        {entries.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-28 gap-4 text-center">
            <div className="w-20 h-20 rounded-full glass flex items-center justify-center mb-2">
              <History size={36} className="text-[var(--text-muted)]" />
            </div>
            <p className="text-2xl font-bold text-[var(--text-secondary)]">Aucun historique</p>
            <p className="text-[var(--text-muted)] text-sm max-w-sm">
              Les vidéos que tu regardes apparaîtront ici automatiquement.
            </p>
            <Link href="/" className="btn btn-primary mt-2">
              Explorer les vidéos
            </Link>
          </div>
        ) : (
          <div className="space-y-10">
            {Object.entries(groupedByDate).map(([date, items]) => (
              <div key={date}>
                <p className="text-xs font-bold uppercase tracking-widest text-[var(--text-muted)] mb-4">
                  {date}
                </p>
                <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-5 gap-x-3 gap-y-7">
                  {items.map((entry) => (
                    <VideoCard key={entry.id} media={entry.media} />
                  ))}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
