"use client";

import { useRef, useEffect, useState } from "react";
import { usePoseDetection, Landmark } from "../hooks/usePoseDetection";
import { calculateSimilarityScore } from "../utils/poseComparison";

interface LivePoseTrackerProps {
  referenceLandmarks: Landmark[] | null;
  isActive: boolean;
  onScoreUpdate?: (score: number) => void;
}

export default function LivePoseTracker({
  referenceLandmarks,
  isActive,
  onScoreUpdate,
}: LivePoseTrackerProps) {
  const videoRef = useRef<HTMLVideoElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [stream, setStream] = useState<MediaStream | null>(null);
  const [error, setError] = useState<string>("");
  const [currentLandmarks, setCurrentLandmarks] = useState<Landmark[] | null>(null);
  const [score, setScore] = useState<number>(0);
  const { detectPose, isReady } = usePoseDetection();
  const animationFrameRef = useRef<number | null>(null);

  // Start webcam
  useEffect(() => {
    const startWebcam = async () => {
      try {
        const mediaStream = await navigator.mediaDevices.getUserMedia({
          video: { width: 640, height: 480, facingMode: "user" },
          audio: false,
        });

        if (videoRef.current) {
          videoRef.current.srcObject = mediaStream;
        }

        setStream(mediaStream);
        setError("");
      } catch (err) {
        setError("Camera access required");
        console.error("Error accessing webcam:", err);
      }
    };

    startWebcam();

    return () => {
      if (stream) {
        stream.getTracks().forEach((track) => track.stop());
      }
    };
  }, []);

  // Detect pose and draw landmarks
  useEffect(() => {
    if (!isActive || !isReady) {
      console.log("LivePoseTracker: Not active or not ready", { isActive, isReady });
      return;
    }

    let lastDetectionTime = 0;
    const DETECTION_INTERVAL = 100; // Detect every 100ms (~10 FPS) to avoid overwhelming the system

    const detectAndDraw = async (timestamp: number) => {
      const video = videoRef.current;
      const canvas = canvasRef.current;

      if (!video || !canvas) {
        animationFrameRef.current = requestAnimationFrame(detectAndDraw);
        return;
      }

      if (video.readyState !== video.HAVE_ENOUGH_DATA) {
        animationFrameRef.current = requestAnimationFrame(detectAndDraw);
        return;
      }

      // Match canvas size to video
      if (canvas.width !== video.videoWidth || canvas.height !== video.videoHeight) {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
      }

      // Throttle detection to avoid overwhelming MediaPipe
      const timeSinceLastDetection = timestamp - lastDetectionTime;
      if (timeSinceLastDetection >= DETECTION_INTERVAL) {
        lastDetectionTime = timestamp;

        try {
          // Detect pose
          const landmarks = await detectPose(video);
          
          if (landmarks) {
            setCurrentLandmarks(landmarks);
            
          // Calculate score if we have reference landmarks
          if (referenceLandmarks) {
            const similarity = calculateSimilarityScore(referenceLandmarks, landmarks);
            setScore(similarity);
            
            // Call callback if provided
            if (onScoreUpdate) {
              onScoreUpdate(similarity);
            }
          } else {
            setScore(0);
            if (onScoreUpdate) {
              onScoreUpdate(0);
            }
          }

            // Draw landmarks
            drawLandmarks(canvas, landmarks);
          } else {
            // No pose detected, clear canvas
            const ctx = canvas.getContext("2d");
            if (ctx) {
              ctx.clearRect(0, 0, canvas.width, canvas.height);
            }
          }
        } catch (error) {
          console.error("Error in detectAndDraw:", error);
        }
      }

      animationFrameRef.current = requestAnimationFrame(detectAndDraw);
    };

    console.log("LivePoseTracker: Starting pose detection loop");
    animationFrameRef.current = requestAnimationFrame(detectAndDraw);

    return () => {
      if (animationFrameRef.current) {
        cancelAnimationFrame(animationFrameRef.current);
      }
    };
  }, [isActive, isReady, detectPose, referenceLandmarks]);

  const drawLandmarks = (canvas: HTMLCanvasElement, landmarks: Landmark[]) => {
    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    // Clear previous drawings
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // Draw connections (bones)
    const connections = [
      // Torso
      [11, 12], // Shoulders
      [11, 23], // Left shoulder to hip
      [12, 24], // Right shoulder to hip
      [23, 24], // Hips
      // Left arm
      [11, 13], // Shoulder to elbow
      [13, 15], // Elbow to wrist
      // Right arm
      [12, 14], // Shoulder to elbow
      [14, 16], // Elbow to wrist
      // Left leg
      [23, 25], // Hip to knee
      [25, 27], // Knee to ankle
      // Right leg
      [24, 26], // Hip to knee
      [26, 28], // Knee to ankle
    ];

    // Draw connections with glow
    connections.forEach(([start, end]) => {
      const startLm = landmarks[start];
      const endLm = landmarks[end];

      if (
        startLm &&
        endLm &&
        startLm.visibility > 0.5 &&
        endLm.visibility > 0.5
      ) {
        // Outer glow
        ctx.strokeStyle = "#00FFFF";
        ctx.lineWidth = 8;
        ctx.globalAlpha = 0.3;
        ctx.shadowBlur = 15;
        ctx.shadowColor = "#00FFFF";
        ctx.beginPath();
        ctx.moveTo(startLm.x * canvas.width, startLm.y * canvas.height);
        ctx.lineTo(endLm.x * canvas.width, endLm.y * canvas.height);
        ctx.stroke();

        // Main line
        ctx.strokeStyle = "#00FFFF";
        ctx.lineWidth = 4;
        ctx.globalAlpha = 1;
        ctx.shadowBlur = 8;
        ctx.beginPath();
        ctx.moveTo(startLm.x * canvas.width, startLm.y * canvas.height);
        ctx.lineTo(endLm.x * canvas.width, endLm.y * canvas.height);
        ctx.stroke();
      }
    });

    // Reset shadow for joints
    ctx.shadowBlur = 0;

    // Draw landmarks (joints) with glow
    landmarks.forEach((landmark) => {
      if (landmark.visibility > 0.5) {
        const x = landmark.x * canvas.width;
        const y = landmark.y * canvas.height;

        // Outer glow
        ctx.fillStyle = "#FFD700";
        ctx.globalAlpha = 0.3;
        ctx.shadowBlur = 12;
        ctx.shadowColor = "#FFD700";
        ctx.beginPath();
        ctx.arc(x, y, 8, 0, 2 * Math.PI);
        ctx.fill();

        // Main circle
        ctx.fillStyle = "#FFD700";
        ctx.globalAlpha = 1;
        ctx.shadowBlur = 6;
        ctx.beginPath();
        ctx.arc(x, y, 5, 0, 2 * Math.PI);
        ctx.fill();

        // Inner highlight
        ctx.fillStyle = "#FFFFFF";
        ctx.globalAlpha = 0.8;
        ctx.shadowBlur = 0;
        ctx.beginPath();
        ctx.arc(x - 1, y - 1, 2, 0, 2 * Math.PI);
        ctx.fill();
      }
    });

    // Reset context
    ctx.globalAlpha = 1;
    ctx.shadowBlur = 0;
  };

  const getScoreColor = (score: number): string => {
    if (score >= 90) return "#FFD700"; // Gold
    if (score >= 80) return "#00FFD1"; // Cyan
    if (score >= 70) return "#4ADE80"; // Green
    if (score >= 60) return "#FBBF24"; // Yellow
    if (score >= 50) return "#F97316"; // Orange
    return "#EF4444"; // Red
  };

  return (
    <div className="relative rounded-2xl overflow-hidden border-2 border-white/20 shadow-2xl bg-black">
      {error && (
        <div className="absolute top-0 left-0 right-0 bg-red-500/90 backdrop-blur-sm text-white p-2 text-center text-sm z-20">
          {error}
        </div>
      )}
      
      {/* Video Feed */}
      <div className="relative aspect-[4/3]">
        <video
          ref={videoRef}
          autoPlay
          playsInline
          muted
          className="absolute inset-0 w-full h-full object-cover"
          style={{ transform: "scaleX(-1)" }}
        />
        
        {/* Landmarks Overlay */}
        <canvas
          ref={canvasRef}
          className="absolute inset-0 w-full h-full pointer-events-none"
          style={{ transform: "scaleX(-1)" }}
        />

        {/* Debug indicator */}
        {currentLandmarks && (
          <div className="absolute top-2 right-2 w-3 h-3 bg-green-500 rounded-full animate-pulse z-10" 
            title="Pose detected"
          />
        )}
      </div>


      {/* Loading indicator */}
      {!isReady && (
        <div className="absolute inset-0 flex flex-col items-center justify-center bg-black/70 backdrop-blur-sm z-30">
          <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-white mb-3"></div>
          <div className="text-white text-sm">Loading pose detection...</div>
        </div>
      )}
    </div>
  );
}

