"use client";

import { use, useRef, useState } from "react";
import { useQuery } from "convex/react";
import { api } from "@/convex/_generated/api";
import { notFound } from "next/navigation";
import Link from "next/link";
import { useScreenRecorder } from "@/lib/useScreenRecorder";
import { uploadToSunoAndGenerateCovers, STYLE_PRESETS } from "@/lib/sunoApi";

export default function GamePage({
  params
}: {
  params: Promise<{ slug: string }>
}) {
  const { slug } = use(params);
  const game = useQuery(api.gamesBySlug.get, { slug });

  const {
    recordingState,
    recordedVideoUrl,
    startRecording,
    stopRecording,
    clearRecording,
    error: recordingError,
  } = useScreenRecorder();

  const [selectedStyle, setSelectedStyle] = useState<string>("relaxing");
  const [isGeneratingSuno, setIsGeneratingSuno] = useState(false);
  const [generatedCovers, setGeneratedCovers] = useState<string[]>([]);
  const [sunoError, setSunoError] = useState<string | null>(null);

  const iframeRef = useRef<HTMLIFrameElement>(null);

  const handleStartRecording = () => {
    if (iframeRef.current) {
      startRecording(iframeRef.current);
    } else {
      startRecording();
    }
  };

  // Extract audio from video
  const extractAudioFromVideo = async (videoUrl: string): Promise<Blob> => {
    return new Promise((resolve, reject) => {
      const video = document.createElement('video');
      video.src = videoUrl;
      video.crossOrigin = 'anonymous';

      video.addEventListener('loadedmetadata', async () => {
        try {
          // Create audio context
          const audioContext = new AudioContext();

          // Create media element source
          const source = audioContext.createMediaElementSource(video);

          // Create destination for recording
          const destination = audioContext.createMediaStreamDestination();
          source.connect(destination);

          // Create MediaRecorder for audio
          const mediaRecorder = new MediaRecorder(destination.stream, {
            mimeType: 'audio/webm',
          });

          const chunks: Blob[] = [];

          mediaRecorder.ondataavailable = (e) => {
            if (e.data.size > 0) {
              chunks.push(e.data);
            }
          };

          mediaRecorder.onstop = () => {
            const audioBlob = new Blob(chunks, { type: 'audio/webm' });
            resolve(audioBlob);
          };

          // Start recording and play video
          mediaRecorder.start();
          video.play();

          // Stop when video ends
          video.addEventListener('ended', () => {
            mediaRecorder.stop();
            audioContext.close();
          });
        } catch (err) {
          reject(err);
        }
      });

      video.addEventListener('error', reject);
    });
  };

  const handleGenerateCovers = async () => {
    if (!recordedVideoUrl) return;

    setIsGeneratingSuno(true);
    setSunoError(null);
    setGeneratedCovers([]);

    try {
      console.log('🎵 Extracting audio from video...');
      const audioBlob = await extractAudioFromVideo(recordedVideoUrl);
      console.log('✅ Audio extracted:', audioBlob.size, 'bytes');

      // Get the style string from the preset
      const styleString = STYLE_PRESETS[selectedStyle as keyof typeof STYLE_PRESETS];

      // Upload to Suno and generate covers
      const result = await uploadToSunoAndGenerateCovers(audioBlob, styleString);

      if (result.success && result.data) {
        // Extract audio URLs from the cover_clips array
        const audioUrls = result.data.cover_clips?.map((clip: any) => clip.audio_url).filter(Boolean) || [];
        setGeneratedCovers(audioUrls);
      } else {
        setSunoError(result.error || 'Failed to generate covers');
      }
    } catch (err) {
      setSunoError(err instanceof Error ? err.message : 'Unknown error occurred');
      console.error('Error generating covers:', err);
    } finally {
      setIsGeneratingSuno(false);
    }
  };

  // Loading state
  if (game === undefined) {
    return (
      <main className="mx-auto max-w-md px-3 py-6">
        <div className="animate-pulse space-y-4">
          <div className="h-8 bg-zinc-200 dark:bg-zinc-800 rounded w-1/3"></div>
          <div className="h-4 bg-zinc-200 dark:bg-zinc-800 rounded w-2/3"></div>
          <div className="aspect-video bg-zinc-200 dark:bg-zinc-800 rounded-2xl"></div>
        </div>
      </main>
    );
  }

  // Not found
  if (game === null) {
    return notFound();
  }

  const sandbox = [
    "allow-scripts",
    "allow-same-origin",
    "allow-pointer-lock",
    "allow-popups-to-escape-sandbox",
  ].join(" ");

  return (
    <main className="mx-auto max-w-md px-3 py-6 space-y-4">
      <Link
        href="/"
        className="inline-flex items-center text-sm text-zinc-500 hover:text-zinc-700 dark:hover:text-zinc-300"
      >
        ← Back to feed
      </Link>

      <div className="space-y-2">
        <h1 className="text-3xl font-bold">{game.title}</h1>
        {game.description && (
          <p className="text-zinc-600 dark:text-zinc-400">{game.description}</p>
        )}
      </div>

      {game.tags && game.tags.length > 0 && (
        <div className="flex flex-wrap gap-2">
          {game.tags.map((tag) => (
            <span
              key={tag}
              className="px-3 py-1 text-xs rounded-full bg-zinc-100 dark:bg-zinc-800 text-zinc-700 dark:text-zinc-300"
            >
              {tag}
            </span>
          ))}
        </div>
      )}

      <div className="flex gap-4 text-sm text-zinc-500">
        <span>{game.plays} plays</span>
        <span>{game.likes} likes</span>
      </div>

      {/* Screen Recording Controls */}
      <div className="space-y-2">
        <div className="flex gap-2 items-center flex-wrap">
          {recordingState === 'idle' && (
            <>
              <button
                onClick={handleStartRecording}
                className="px-4 py-2 rounded-lg font-medium bg-red-500 hover:bg-red-600 text-white transition-all shadow-lg"
              >
                🎥 Record Game
              </button>
              <span className="text-sm text-zinc-500">
                (Check &quot;Share tab audio&quot; in browser dialog)
              </span>
            </>
          )}
          {recordingState === 'recording' && (
            <>
              <button
                onClick={stopRecording}
                className="px-4 py-2 rounded-lg font-medium bg-red-600 hover:bg-red-700 text-white animate-pulse transition-all shadow-lg"
              >
                ⏹ Stop Recording
              </button>
              <span className="text-sm text-red-500 animate-pulse font-medium">● Recording...</span>
            </>
          )}
          {recordingState === 'recorded' && (
            <>
              <button
                onClick={clearRecording}
                className="px-4 py-2 rounded-lg font-medium bg-gray-700 hover:bg-gray-600 text-white transition-all shadow-lg"
              >
                🗑 Clear Video
              </button>
              <button
                onClick={handleStartRecording}
                className="px-4 py-2 rounded-lg font-medium bg-red-500 hover:bg-red-600 text-white transition-all shadow-lg"
              >
                🎥 Record Again
              </button>
            </>
          )}
        </div>
      </div>

      {recordingError && (
        <div className="bg-red-500/20 border border-red-500 rounded-lg p-3 text-sm text-red-300">
          {recordingError}
        </div>
      )}

      <div className="relative w-full h-[600px] sm:h-[700px] md:h-[800px] lg:h-[900px] overflow-hidden rounded-2xl border border-zinc-200 dark:border-zinc-800">
        <iframe
          ref={iframeRef}
          title={game.title}
          src={game.srcUrl}
          className="w-full h-full"
          loading="eager"
          referrerPolicy="no-referrer"
          sandbox={sandbox}
          allow="gamepad *; accelerometer *; autoplay *; midi *; clipboard-read *; clipboard-write *"
        />
      </div>

      {/* Recorded Video Display */}
      {recordedVideoUrl && (
        <div className="p-6 bg-black/40 backdrop-blur-sm rounded-2xl shadow-2xl border border-zinc-200 dark:border-zinc-800 space-y-4">
          <div>
            <h3 className="text-lg font-bold mb-4">📹 Recorded Video</h3>
            <video
              controls
              src={recordedVideoUrl}
              className="w-full rounded-xl"
            />
          </div>

          {/* Suno Cover Generation */}
          <div className="border-t border-zinc-700 pt-4">
            <h3 className="text-lg font-bold mb-4">🎵 Generate AI Covers with Suno</h3>

            <div className="flex flex-col gap-4">
              <div className="flex gap-3 items-center flex-wrap">
                <div className="flex-1 min-w-[200px]">
                  <label className="block text-sm font-medium mb-2 text-white">
                    Select Style:
                  </label>
                  <select
                    value={selectedStyle}
                    onChange={(e) => setSelectedStyle(e.target.value)}
                    disabled={isGeneratingSuno}
                    className="w-full px-4 py-2 rounded-lg bg-gray-800 text-white border border-gray-600 focus:border-purple-500 focus:outline-none disabled:opacity-50"
                  >
                    {Object.keys(STYLE_PRESETS).map((style) => (
                      <option key={style} value={style}>
                        {style.charAt(0).toUpperCase() + style.slice(1)}
                      </option>
                    ))}
                  </select>
                </div>

                <button
                  onClick={handleGenerateCovers}
                  disabled={isGeneratingSuno}
                  className="px-6 py-2 mt-7 rounded-lg font-bold bg-purple-600 hover:bg-purple-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white shadow-lg transition-all"
                >
                  {isGeneratingSuno ? '⏳ Generating...' : '✨ Generate Covers'}
                </button>
              </div>

              {sunoError && (
                <div className="bg-red-500/20 border border-red-500 rounded-lg p-3">
                  <p className="text-red-300 text-sm">❌ {sunoError}</p>
                </div>
              )}

              {isGeneratingSuno && (
                <div className="flex items-center gap-2 bg-purple-500/20 backdrop-blur-sm px-4 py-3 rounded-lg border border-purple-500">
                  <div className="w-3 h-3 bg-purple-500 rounded-full animate-pulse" />
                  <span className="text-white text-sm">Generating AI covers... This may take a moment.</span>
                </div>
              )}

              {generatedCovers.length > 0 && (
                <div className="space-y-3">
                  <h4 className="text-white font-semibold">Generated Covers:</h4>
                  {generatedCovers.map((url, index) => (
                    <div key={index} className="bg-gray-800/50 p-3 rounded-lg">
                      <p className="text-white text-sm mb-2">Cover {index + 1}</p>
                      <audio
                        controls
                        src={url}
                        className="w-full"
                      />
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      <div className="pt-4 space-y-4">
        <h2 className="text-xl font-semibold">About this game</h2>
        <div className="prose dark:prose-invert">
          <p className="text-zinc-600 dark:text-zinc-400">
            {game.description || "No description available."}
          </p>
        </div>
      </div>
    </main>
  );
}
