import prisma from "@/lib/prisma";
import Link from "next/link";
import Image from "next/image";

export const metadata = {
  title: "LiveCam - Live Adult Cam Shows | AdultWorld",
  description: "Watch live cam shows from verified performers. Free, group, and private shows available.",
  alternates: {
    canonical: "/livecam",
  },
  openGraph: {
    title: "LiveCam - Live Adult Cam Shows | AdultWorld",
    description: "Watch live cam shows from verified performers. Free, group, and private shows available.",
  },
};

interface LiveCamRow {
  id: number;
  user_id: number;
  free_max_minutes: number;
  group_rate: number;
  private_rate: number;
  category: string;
  strapline: string;
  is_live: boolean;
  username: string | null;
  profile_photo: string | null;
  viewer_count: number;
  session_id: number | null;
  mode: string | null;
}

export default async function LiveCamBrowsePage() {
  let liveCams: LiveCamRow[] = [];

  try {
    liveCams = await prisma.$queryRawUnsafe<LiveCamRow[]>(
      `SELECT
        lcs.id,
        lcs.user_id,
        lcs.free_max_minutes,
        lcs.group_rate,
        lcs.private_rate,
        lcs.category,
        lcs.strapline,
        lcs.is_live,
        u.username,
        u.profile_photo,
        COALESCE(ls.viewer_count, 0) AS viewer_count,
        ls.id AS session_id,
        ls.mode
      FROM live_cam_settings lcs
      JOIN users u ON u.id = lcs.user_id
      LEFT JOIN live_sessions ls ON ls.user_id = lcs.user_id AND ls.ended_at IS NULL
      WHERE lcs.is_live = true
      ORDER BY COALESCE(ls.viewer_count, 0) DESC`
    );
  } catch {
    // Table might not exist yet
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-white">LiveCam</h1>
        <p className="text-text-muted mt-1">Watch live cam shows from verified performers</p>
      </div>

      {liveCams.length > 0 ? (
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
          {liveCams.map((cam) => (
            <Link
              key={cam.id}
              href={`/livecam/${cam.user_id}`}
              className="bg-surface rounded-xl overflow-hidden border border-white/5 hover:border-gold/30 transition-all group"
            >
              {/* Thumbnail */}
              <div className="aspect-video bg-surface-light relative flex items-center justify-center">
                {cam.profile_photo ? (
                  <Image
                    src={cam.profile_photo}
                    alt={cam.username || "Performer"}
                    fill
                    sizes="(max-width:640px) 100vw, (max-width:1024px) 50vw, 25vw"
                    className="object-cover"
                  />
                ) : (
                  <svg className="w-12 h-12 text-text-muted" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
                  </svg>
                )}

                {/* LIVE badge */}
                <span className="absolute top-2 left-2 bg-red-600 text-white text-xs font-bold px-2 py-0.5 rounded flex items-center gap-1">
                  <span className="w-1.5 h-1.5 bg-white rounded-full animate-pulse" />
                  LIVE
                </span>

                {/* Mode badge */}
                <span
                  className={`absolute top-2 right-2 text-white text-xs font-bold px-2 py-0.5 rounded uppercase ${
                    cam.mode === "private"
                      ? "bg-purple-600"
                      : cam.mode === "group"
                      ? "bg-blue-600"
                      : "bg-green-600"
                  }`}
                >
                  {cam.mode || "Free"}
                </span>

                {/* Viewer count */}
                <span className="absolute bottom-2 right-2 bg-black/60 text-white text-xs px-2 py-0.5 rounded flex items-center gap-1">
                  <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
                    <path d="M10 12a2 2 0 100-4 2 2 0 000 4z" />
                    <path fillRule="evenodd" d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z" clipRule="evenodd" />
                  </svg>
                  {Number(cam.viewer_count)}
                </span>
              </div>

              {/* Info */}
              <div className="p-3 space-y-1">
                <p className="font-semibold text-white truncate group-hover:text-gold transition-colors">
                  {cam.username || "Performer"}
                </p>
                {cam.strapline && (
                  <p className="text-text-muted text-xs truncate">{cam.strapline}</p>
                )}
                <div className="flex items-center justify-between text-xs">
                  <span className="text-text-muted">{cam.category}</span>
                  <span className="text-gold font-semibold">
                    {Number(cam.group_rate) > 0
                      ? `${cam.group_rate} cr/min`
                      : "Free"}
                  </span>
                </div>
              </div>
            </Link>
          ))}
        </div>
      ) : (
        <div className="text-center py-20">
          <svg className="w-16 h-16 mx-auto text-text-muted mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
          </svg>
          <p className="text-lg text-text-muted">No live cams right now — check back later</p>
        </div>
      )}
    </div>
  );
}
