"use client";

import { useState, useRef } from "react";
import WebcamCapture from "./components/WebcamCapture";
import PoseLandmarks from "./components/PoseLandmarks";

interface Landmark {
  x: number;
  y: number;
  z: number;
  visibility: number;
}

export default function Home() {
  const [referenceImage, setReferenceImage] = useState<string | null>(null);
  const [score, setScore] = useState<number | null>(null);
  const [isComparing, setIsComparing] = useState(false);
  const [message, setMessage] = useState<string>("");
  const [referenceLandmarks, setReferenceLandmarks] = useState<
    Landmark[] | null
  >(null);
  const [currentLandmarks, setCurrentLandmarks] = useState<Landmark[] | null>(
    null
  );
  const [showLandmarks, setShowLandmarks] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const referenceImageRef = useRef<HTMLImageElement>(null);
  const webcamVideoRef = useRef<HTMLVideoElement>(null);

  const BACKEND_URL = "http://localhost:8000";

  const handleReferenceUpload = async (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // Display the image
    const reader = new FileReader();
    reader.onload = (e) => {
      setReferenceImage(e.target?.result as string);
    };
    reader.readAsDataURL(file);

    // Send to backend
    const formData = new FormData();
    formData.append("file", file);

    try {
      const response = await fetch(`${BACKEND_URL}/api/set-reference`, {
        method: "POST",
        body: formData,
      });

      if (response.ok) {
        const data = await response.json();
        setMessage(
          `Reference pose set! Detected ${data.landmarks_detected} landmarks.`
        );
        setReferenceLandmarks(data.landmarks);
      } else {
        const error = await response.json();
        setMessage(`Error: ${error.detail}`);
      }
    } catch (error) {
      setMessage(
        "Error connecting to backend. Make sure it's running on port 8000."
      );
      console.error("Error uploading reference:", error);
    }
  };

  const handleFrameCapture = async (blob: Blob) => {
    if (!isComparing) return;

    const formData = new FormData();
    formData.append("file", blob, "frame.jpg");

    try {
      const response = await fetch(`${BACKEND_URL}/api/compare-pose`, {
        method: "POST",
        body: formData,
      });

      if (response.ok) {
        const data = await response.json();
        setScore(data.score);
        if (data.current_landmarks) {
          setCurrentLandmarks(data.current_landmarks);
        }
        if (data.message) {
          setMessage(data.message);
        }
      } else {
        const error = await response.json();
        console.error("Error comparing pose:", error.detail);
      }
    } catch (error) {
      console.error("Error comparing pose:", error);
    }
  };

  const getScoreColor = (score: number) => {
    if (score >= 80) return "text-green-500";
    if (score >= 60) return "text-yellow-500";
    if (score >= 40) return "text-orange-500";
    return "text-red-500";
  };

  const getScoreEmoji = (score: number) => {
    if (score >= 90) return "🔥";
    if (score >= 80) return "💃";
    if (score >= 70) return "👍";
    if (score >= 60) return "😊";
    if (score >= 40) return "🤔";
    return "💪";
  };

  return (
    <main className="min-h-screen bg-linear-to-br from-purple-900 via-blue-900 to-pink-900 p-8">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="text-center mb-8">
          <h1 className="text-6xl font-bold text-white mb-2 drop-shadow-lg">
            💃 Dancify 🕺
          </h1>
          <p className="text-xl text-purple-200">
            Strike a pose and match the reference frame!
          </p>
          <p className="text-sm text-purple-300 mt-4">
            💡 To use with a song, visit:{" "}
            <code className="bg-black/30 px-2 py-1 rounded">/[songId]</code>
          </p>
        </div>

        {/* Instructions */}
        {!referenceImage && (
          <div className="bg-white/10 backdrop-blur-md rounded-lg p-6 mb-8 text-center">
            <h2 className="text-2xl font-semibold text-white mb-2">
              Getting Started
            </h2>
            <p className="text-purple-200">
              Upload a reference pose image to begin. Make sure a person is
              clearly visible in the photo!
            </p>
          </div>
        )}

        {/* Message Display */}
        {message && (
          <div className="bg-blue-500/20 backdrop-blur-md rounded-lg p-4 mb-6 text-center">
            <p className="text-white">{message}</p>
          </div>
        )}

        {/* Main Content Grid */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
          {/* Reference Image Section */}
          <div className="bg-white/10 backdrop-blur-md rounded-xl p-6">
            <h2 className="text-2xl font-semibold text-white mb-4">
              Reference Pose
            </h2>

            {!referenceImage ? (
              <div className="border-4 border-dashed border-purple-300 rounded-lg p-12 text-center">
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/*"
                  onChange={handleReferenceUpload}
                  className="hidden"
                />
                <button
                  onClick={() => fileInputRef.current?.click()}
                  className="bg-purple-600 hover:bg-purple-700 text-white font-bold py-4 px-8 rounded-lg transition-colors"
                >
                  Upload Reference Image
                </button>
                <p className="text-purple-200 mt-4">
                  Click to select a pose image
                </p>
              </div>
            ) : (
              <div className="relative">
                <img
                  ref={referenceImageRef}
                  src={referenceImage}
                  alt="Reference pose"
                  className="w-full h-auto rounded-lg shadow-lg border-4 border-purple-500"
                />
                {showLandmarks && (
                  <PoseLandmarks
                    landmarks={referenceLandmarks}
                    imageRef={referenceImageRef.current}
                  />
                )}
                <button
                  onClick={() => {
                    setReferenceImage(null);
                    setScore(null);
                    setIsComparing(false);
                    setReferenceLandmarks(null);
                    setCurrentLandmarks(null);
                    fileInputRef.current?.click();
                  }}
                  className="absolute top-2 right-2 bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg transition-colors hover:cursor-pointer"
                >
                  Change
                </button>
              </div>
            )}
          </div>

          {/* Webcam Section */}
          <div className="bg-white/10 backdrop-blur-md rounded-xl p-6">
            <h2 className="text-2xl font-semibold text-white mb-4">
              Your Pose
            </h2>

            {referenceImage ? (
              <div className="relative">
                <WebcamCapture
                  onFrameCapture={handleFrameCapture}
                  captureInterval={500}
                  isActive={isComparing}
                  videoRef={webcamVideoRef}
                />
                {showLandmarks && (
                  <PoseLandmarks
                    landmarks={currentLandmarks}
                    imageRef={webcamVideoRef.current}
                  />
                )}
              </div>
            ) : (
              <div className="border-4 border-dashed border-gray-500 rounded-lg p-12 text-center">
                <p className="text-gray-400">Upload a reference image first</p>
              </div>
            )}
          </div>
        </div>

        {/* Score Display and Controls */}
        {referenceImage && (
          <div className="bg-white/10 backdrop-blur-md rounded-xl p-8 text-center">
            {score !== null && (
              <div className="mb-6">
                <div
                  className={`text-8xl font-bold ${getScoreColor(
                    score
                  )} drop-shadow-lg mb-2`}
                >
                  {score} {getScoreEmoji(score)}
                </div>
                <p className="text-2xl text-white">Similarity Score</p>
              </div>
            )}

            <div className="flex gap-4 justify-center items-center flex-wrap">
              <button
                onClick={() => setIsComparing(!isComparing)}
                className={`${
                  isComparing
                    ? "bg-red-600 hover:bg-red-700"
                    : "bg-green-600 hover:bg-green-700"
                } text-white font-bold py-4 px-12 rounded-lg transition-colors text-xl hover:cursor-pointer`}
              >
                {isComparing ? "Stop Comparing" : "Start Comparing"}
              </button>

              <button
                onClick={() => setShowLandmarks(!showLandmarks)}
                className={`${
                  showLandmarks
                    ? "bg-cyan-600 hover:bg-cyan-700"
                    : "bg-purple-600 hover:bg-purple-700"
                } text-white font-bold py-4 px-12 rounded-lg transition-colors text-xl hover:cursor-pointer`}
              >
                {showLandmarks ? "Hide Landmarks" : "Show Landmarks"}
              </button>
            </div>

            {!isComparing && score === null && (
              <p className="text-purple-200 mt-4">
                Click to start real-time pose comparison
              </p>
            )}
          </div>
        )}

        {/* Footer */}
        <div className="mt-12 text-center text-purple-300">
          <p>
            Powered by{" "}
            <a
              href="https://suno.com"
              target="_blank"
              rel="noopener noreferrer"
              className="text-orange-300 hover:text-orange-400"
            >
              Suno
            </a>
            {" & built with ❤️ by Krish, Eric, and Fahmi!"}
          </p>
        </div>
      </div>
    </main>
  );
}
