"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import Image from "next/image";

interface LiveCam {
  id: number;
  user_id: number;
  username: string | null;
  profile_photo: string | null;
  viewer_count: number;
  mode: string | null;
  strapline: string | null;
  category: string | null;
  group_rate: number;
}

export default function MultiCamGridPage() {
  const [cams, setCams] = useState<LiveCam[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Fetch live cams from the public livecam API.
    // The earlier `fetchLiveCams` helper hit /api/livecam/session?broadcaster_id=0
    // which always 404'd (no broadcaster id 0). Removed — `loadCams` does
    // the right thing.
    async function loadCams() {
      try {
        const res = await fetch("/api/livecam/browse");
        if (res.ok) {
          const json = await res.json();
          setCams((json.data || []).slice(0, 4));
        }
      } catch {
        // Table might not exist yet
      } finally {
        setLoading(false);
      }
    }

    loadCams();

    // Refresh every 30 seconds
    const interval = setInterval(loadCams, 30000);
    return () => clearInterval(interval);
  }, []);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="w-8 h-8 border-2 border-gold border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }

  return (
    <div className="max-w-6xl mx-auto space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Multi-Cam View</h1>
          <p className="text-text-muted mt-1">Watch up to 4 live cams at once</p>
        </div>
        <Link
          href="/livecam"
          className="text-gold hover:text-gold-light text-sm transition-colors"
        >
          Browse all cams
        </Link>
      </div>

      {cams.length > 0 ? (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {cams.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"
            >
              {/* Video area */}
              <div className="aspect-video bg-black relative flex items-center justify-center">
                {cam.profile_photo ? (
                  <Image
                    src={cam.profile_photo}
                    alt={cam.username || "Performer"}
                    fill
                    sizes="(max-width:768px) 100vw, 50vw"
                    className="object-cover"
                  />
                ) : (
                  <svg
                    className="w-16 h-16 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>

                {/* Play overlay */}
                <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity bg-black/30">
                  <div className="bg-gold/90 rounded-full p-3">
                    <svg className="w-8 h-8 text-black" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M8 5v14l11-7z" />
                    </svg>
                  </div>
                </div>
              </div>

              {/* Info bar */}
              <div className="p-3 flex items-center justify-between">
                <div>
                  <p className="font-semibold text-white group-hover:text-gold transition-colors">
                    {cam.username || "Performer"}
                  </p>
                  {cam.strapline && (
                    <p className="text-text-muted text-xs truncate max-w-[200px]">{cam.strapline}</p>
                  )}
                </div>
                <span className="text-gold font-semibold text-sm">
                  {Number(cam.group_rate) > 0 ? `${cam.group_rate} cr/min` : "Free"}
                </span>
              </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</p>
          <p className="text-text-muted text-sm mt-1">Check back later or browse all cams</p>
          <Link
            href="/livecam"
            className="inline-block mt-4 bg-gold hover:bg-gold-light text-black font-semibold px-6 py-2 rounded-lg transition-all"
          >
            Browse LiveCams
          </Link>
        </div>
      )}

      {/* Empty slots if less than 4 cams */}
      {cams.length > 0 && cams.length < 4 && (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {Array.from({ length: 4 - cams.length }).map((_, i) => (
            <div
              key={`empty-${i}`}
              className="bg-surface rounded-xl border border-dashed border-surface-light aspect-video flex items-center justify-center"
            >
              <div className="text-center text-text-muted">
                <svg
                  className="w-10 h-10 mx-auto mb-2"
                  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-sm">Waiting for stream...</p>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
