import { auth } from "@/lib/auth";
import prisma from "@/lib/prisma";
import EscortCard from "./escort-card";
import { withAvatarUrls } from "@/lib/media";

export default async function RecentlyViewed() {
  const session = await auth();
  if (!session?.user?.id) return null;

  const userId = Number(session.user.id);

  let recentlyViewed: { viewed_user_id: number; viewed_at: Date }[] = [];
  try {
    recentlyViewed = await prisma.$queryRawUnsafe(
      `SELECT DISTINCT ON (viewed_user_id) viewed_user_id, viewed_at
       FROM recently_viewed
       WHERE user_id = $1
       ORDER BY viewed_user_id, viewed_at DESC`,
      userId
    );
  } catch {
    // Table may not exist yet
    return null;
  }

  if (recentlyViewed.length === 0) return null;

  // Sort by most recent
  recentlyViewed.sort(
    (a, b) => new Date(b.viewed_at).getTime() - new Date(a.viewed_at).getTime()
  );

  const viewedIds = recentlyViewed.slice(0, 10).map((r) => r.viewed_user_id);

  const users = await prisma.user.findMany({
    where: { id: { in: viewedIds }, active: true, banned_at: null },
    include: { country: true, city: true },
  });

  if (users.length === 0) return null;

  // Maintain order
  const userMap = new Map(users.map((u) => [u.id, u]));
  const orderedRaw = viewedIds
    .map((id) => userMap.get(id))
    .filter((u): u is NonNullable<typeof u> => u != null);
  const ordered = await withAvatarUrls(orderedRaw);

  if (ordered.length === 0) return null;

  return (
    <section>
      <div className="flex items-center justify-between mb-5">
        <div className="flex items-center gap-3">
          <svg className="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          <h2 className="text-xl md:text-2xl font-bold">Recently Viewed</h2>
        </div>
      </div>
      <div className="flex gap-4 overflow-x-auto pb-4 scrollbar-thin scrollbar-thumb-surface-light snap-x snap-mandatory">
        {ordered.map((escort) => (
          <div key={escort.id} className="flex-shrink-0 w-44 md:w-48 snap-start">
            <EscortCard escort={escort} />
          </div>
        ))}
      </div>
    </section>
  );
}
