'use client';

import React, { useState, useEffect } from 'react';
import { ShieldCheck, Lock, Loader2, AlertCircle } from 'lucide-react';
import { apiRequest } from '@/lib/api';

interface SecureVideoPlayerProps {
  fileKey: string;
  courseId: string;
  title?: string;
  fullScreenDirect?: boolean;
}

export default function SecureVideoPlayer({
  fileKey,
  courseId,
  title = 'German Course Video Lesson',
  fullScreenDirect = false,
}: SecureVideoPlayerProps) {
  const [streamUrl, setStreamUrl] = useState<string | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!fileKey) {
      setError('Video file reference key missing.');
      setLoading(false);
      return;
    }

    let currentObjectUrl: string | null = null;

    const fetchSignedStreamUrl = async () => {
      setLoading(true);
      setError(null);

      try {
        const res = await apiRequest(
          `/videos/secure-stream?fileKey=${encodeURIComponent(fileKey)}&courseId=${courseId}`
        );

        if (res.success && res.streamUrl) {
          // Fetch stream directly into a blob to obscure the raw stream URL from DOM inspection
          const mediaResp = await fetch(res.streamUrl, {
            headers: {
              'Accept': 'video/mp4,video/*',
            },
          });

          if (!mediaResp.ok) {
            throw new Error(`Failed to load video data (${mediaResp.status})`);
          }

          const blob = await mediaResp.blob();
          currentObjectUrl = URL.createObjectURL(blob);
          setStreamUrl(currentObjectUrl);
        } else {
          setError(res.error || 'Unable to authorize video playback stream.');
        }
      } catch (err: any) {
        setError(err.message || 'Error fetching secure video stream.');
      } finally {
        setLoading(false);
      }
    };

    fetchSignedStreamUrl();

    return () => {
      if (currentObjectUrl) {
        URL.revokeObjectURL(currentObjectUrl);
      }
    };
  }, [fileKey, courseId]);

  const videoRef = React.useRef<HTMLVideoElement>(null);

  // Auto request Fullscreen when streamUrl is ready
  useEffect(() => {
    if (streamUrl && videoRef.current) {
      const vid = videoRef.current;
      vid.play().catch(() => {});
      
      if (vid.requestFullscreen) {
        vid.requestFullscreen().catch(() => {});
      } else if ((vid as any).webkitRequestFullscreen) {
        (vid as any).webkitRequestFullscreen();
      } else if ((vid as any).msRequestFullscreen) {
        (vid as any).msRequestFullscreen();
      }
    }
  }, [streamUrl]);

  const [isScreenRecordingBlocked, setIsScreenRecordingBlocked] = useState<boolean>(false);

  // Screen Capture & Hardware Recorder Detection Protection
  useEffect(() => {
    // 1. Detect window blur / focus loss (triggered by screen recorder overlays, OBS, Camtasia, Loom, Windows Game Bar)
    const handleBlur = () => {
      setIsScreenRecordingBlocked(true);
      if (videoRef.current) {
        videoRef.current.pause();
      }
    };

    const handleFocus = () => {
      setIsScreenRecordingBlocked(false);
      if (videoRef.current) {
        videoRef.current.play().catch(() => {});
      }
    };

    // 2. Detect tab switching / minimization / screen sharing
    const handleVisibilityChange = () => {
      if (document.hidden) {
        setIsScreenRecordingBlocked(true);
        if (videoRef.current) {
          videoRef.current.pause();
        }
      } else {
        setIsScreenRecordingBlocked(false);
        if (videoRef.current) {
          videoRef.current.play().catch(() => {});
        }
      }
    };

    // 3. Monitor Display Media / Screen Capture API activation
    let mediaTrackCheckInterval: any = null;
    const checkActiveScreenSharing = () => {
      if (navigator.mediaDevices && (navigator.mediaDevices as any).getDisplayMedia) {
        // If display media capture is initiated, block player output
        if ((window as any).isDisplayCaptureActive) {
          setIsScreenRecordingBlocked(true);
          if (videoRef.current) videoRef.current.pause();
        }
      }
    };
    mediaTrackCheckInterval = setInterval(checkActiveScreenSharing, 800);

    // 4. Wipe console logs & disable capture shortcuts
    const clearConsoleInterval = setInterval(() => {
      try {
        console.clear();
      } catch (e) {}
    }, 400);

    const handleKeyDown = (e: KeyboardEvent) => {
      if (
        e.key === 'F12' ||
        (e.ctrlKey && e.shiftKey && (e.key === 'I' || e.key === 'i' || e.key === 'J' || e.key === 'j' || e.key === 'C' || e.key === 'c')) ||
        (e.ctrlKey && (e.key === 'U' || e.key === 'u' || e.key === 'S' || e.key === 's' || e.key === 'P' || e.key === 'p')) ||
        e.key === 'PrintScreen'
      ) {
        e.preventDefault();
        e.stopPropagation();
        setIsScreenRecordingBlocked(true);
        setTimeout(() => setIsScreenRecordingBlocked(false), 2500);
        return false;
      }
    };

    const handleContextMenu = (e: MouseEvent) => {
      e.preventDefault();
    };

    window.addEventListener('blur', handleBlur);
    window.addEventListener('focus', handleFocus);
    document.addEventListener('visibilitychange', handleVisibilityChange);
    window.addEventListener('keydown', handleKeyDown);
    window.addEventListener('contextmenu', handleContextMenu);

    return () => {
      if (clearConsoleInterval) clearInterval(clearConsoleInterval);
      if (mediaTrackCheckInterval) clearInterval(mediaTrackCheckInterval);
      window.removeEventListener('blur', handleBlur);
      window.removeEventListener('focus', handleFocus);
      document.removeEventListener('visibilitychange', handleVisibilityChange);
      window.removeEventListener('keydown', handleKeyDown);
      window.removeEventListener('contextmenu', handleContextMenu);
    };
  }, []);

  const [videoError, setVideoError] = useState<boolean>(false);
  const canvasRef = React.useRef<HTMLCanvasElement>(null);
  const [isPlaying, setIsPlaying] = useState<boolean>(true);
  const [watermarkPos, setWatermarkPos] = useState({ top: '20%', left: '20%' });

  // Render video frames onto Canvas 2D context to defeat standard OS screen recording capture tools
  useEffect(() => {
    const video = videoRef.current;
    const canvas = canvasRef.current;
    if (!video || !canvas || !streamUrl) return;

    const ctx = canvas.getContext('2d', {
      willReadFrequently: false,
      alpha: false, // Prevents OS window compositor from extracting transparent background layers
    });

    let animationFrameId: number;

    const drawFrame = () => {
      if (video.paused || video.ended) return;

      if (ctx) {
        if (canvas.width !== video.videoWidth && video.videoWidth > 0) {
          canvas.width = video.videoWidth;
          canvas.height = video.videoHeight;
        }
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      }

      animationFrameId = requestAnimationFrame(drawFrame);
    };

    const handlePlay = () => {
      setIsPlaying(true);
      drawFrame();
    };

    const handlePause = () => {
      setIsPlaying(false);
      cancelAnimationFrame(animationFrameId);
    };

    video.addEventListener('play', handlePlay);
    video.addEventListener('pause', handlePause);

    if (!video.paused) {
      drawFrame();
    }

    return () => {
      video.removeEventListener('play', handlePlay);
      video.removeEventListener('pause', handlePause);
      cancelAnimationFrame(animationFrameId);
    };
  }, [streamUrl]);

  // Shift dynamic watermark every 12 seconds
  useEffect(() => {
    const interval = setInterval(() => {
      const topPos = Math.floor(Math.random() * 65 + 15) + '%';
      const leftPos = Math.floor(Math.random() * 55 + 15) + '%';
      setWatermarkPos({ top: topPos, left: leftPos });
    }, 12000);

    return () => clearInterval(interval);
  }, []);

  if (loading) {
    return (
      <div className={`w-full ${fullScreenDirect ? 'h-screen' : 'aspect-video rounded-2xl'} bg-slate-950 flex flex-col items-center justify-center text-white space-y-3 p-6`}>
        <Loader2 className="w-10 h-10 animate-spin text-amber-400" />
        <p className="text-sm font-bold text-slate-300">Authorizing & loading full screen video stream...</p>
      </div>
    );
  }

  if (error || !streamUrl || videoError) {
    return (
      <div className={`w-full ${fullScreenDirect ? 'h-screen' : 'aspect-video rounded-2xl'} bg-slate-950 flex flex-col items-center justify-center text-red-300 p-6 space-y-3 text-center`}>
        <AlertCircle className="w-12 h-12 text-red-400 animate-pulse" />
        <div className="space-y-1">
          <p className="text-base font-extrabold text-red-200">
            {videoError
              ? 'Video Playback Error'
              : error || 'Video Stream Unavailable'}
          </p>
          <p className="text-xs text-red-300/80 max-w-md leading-relaxed">
            {videoError
              ? `The file "${fileKey}" was not found in S3 bucket "apkagermanschool" or could not be loaded.`
              : 'Please verify your course subscription status or contact support.'}
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className={`w-full ${fullScreenDirect ? 'h-screen' : 'space-y-3'} select-none`} onContextMenu={(e) => e.preventDefault()}>
      {/* HTML5 Protected Canvas Player Container */}
      <div 
        className={`relative w-full ${fullScreenDirect ? 'h-full rounded-none border-none' : 'aspect-video rounded-2xl border border-gray-200'} overflow-hidden bg-black shadow-2xl select-none`}
        onContextMenu={(e) => e.preventDefault()}
      >
        {/* Anti-Screen Recording Blackout Overlay */}
        {isScreenRecordingBlocked && (
          <div className="absolute inset-0 z-50 bg-black flex flex-col items-center justify-center text-white p-6 space-y-3 text-center">
            <ShieldCheck className="w-12 h-12 text-amber-400 animate-pulse" />
            <div className="space-y-1">
              <p className="text-base font-extrabold text-amber-200">
                Protected Video Stream
              </p>
              <p className="text-xs text-slate-300 max-w-md leading-relaxed">
                Screen recording and external window capture are disabled for copyright protection. Return focus to the video window to resume playback.
              </p>
            </div>
          </div>
        )}

        {/* Dynamic Watermark Overlay */}
        {!isScreenRecordingBlocked && (
          <div
            style={{ top: watermarkPos.top, left: watermarkPos.left }}
            className="absolute z-40 pointer-events-none transition-all duration-1000 ease-in-out opacity-40 select-none"
          >
            <div className="bg-black/70 backdrop-blur-xs text-amber-300 text-[10px] font-mono px-2.5 py-1 rounded border border-amber-400/20 shadow-md flex items-center gap-1.5">
              <Lock className="w-3 h-3 text-amber-400" />
              <span>Apka German School Protected</span>
            </div>
          </div>
        )}

        {/* Hidden HTML5 Video Source */}
        <video
          ref={videoRef}
          src={streamUrl}
          controls
          autoPlay
          controlsList="nodownload noremoteplayback"
          disablePictureInPicture
          onContextMenu={(e) => e.preventDefault()}
          onError={() => setVideoError(true)}
          aria-label={title}
          className="w-full h-full object-contain select-none pointer-events-auto"
        />

        {/* Protected Canvas Layer (Screen Recorders capture black buffer frame) */}
        <canvas
          ref={canvasRef}
          className={`absolute inset-0 w-full h-full object-contain pointer-events-none ${
            isScreenRecordingBlocked ? 'opacity-0' : 'opacity-100'
          }`}
        />
      </div>
    </div>
  );
}
