import { useEffect, useRef, useState } from "react";
import type { RecordingMode } from "@/hooks/use-recording-mode";
import { AudioLevelBars } from "@/components/audio/audio-level-bars";
import { useAudioSource } from "@/components/audio/use-audio-source";

interface RecordingOverlayProps {
  step: "recording" | "reviewing";
  mediaStream: MediaStream | null;
  recordingMode: RecordingMode;
  reviewBlob: Blob | null;
  error: string | null;
  onClose: () => void;
}

function RecordingTimer() {
  const [elapsed, setElapsed] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setElapsed((prev) => prev + 1);
    }, 1000);
    return () => clearInterval(interval);
  }, []);

  const minutes = Math.floor(elapsed / 60);
  const seconds = elapsed % 60;
  const display = `${minutes}:${seconds.toString().padStart(2, "0")}`;

  return (
    <div className="flex items-center gap-2">
      <span className="h-2.5 w-2.5 animate-pulse rounded-full bg-red-500" />
      <span className="font-mono text-sm text-white/80">{display}</span>
    </div>
  );
}

function ReviewPlayback({
  blob,
  isVideo,
}: {
  blob: Blob;
  isVideo: boolean;
}) {
  const urlRef = useRef<string | null>(null);
  const [objectUrl, setObjectUrl] = useState<string | null>(null);
  const audioElRef = useRef<HTMLAudioElement | null>(null);
  const [audioEl, setAudioEl] = useState<HTMLAudioElement | null>(null);
  const audioSource = useAudioSource(isVideo ? null : audioEl);

  useEffect(() => {
    const url = URL.createObjectURL(blob);
    urlRef.current = url;
    setObjectUrl(url);

    return () => {
      URL.revokeObjectURL(url);
      urlRef.current = null;
    };
  }, [blob]);

  if (!objectUrl) return null;

  if (isVideo) {
    return (
      <video
        src={objectUrl}
        autoPlay
        loop
        playsInline
        className="absolute inset-0 h-full w-full -scale-x-100 object-cover"
      />
    );
  }

  return (
    <div className="flex flex-col items-center gap-3">
      <audio
        ref={(el) => {
          audioElRef.current = el;
          setAudioEl(el);
        }}
        src={objectUrl}
        autoPlay
        loop
      />
      {audioSource ? (
        <AudioLevelBars sourceNode={audioSource.sourceNode} />
      ) : (
        <span className="text-sm text-white/60">Playing back audio...</span>
      )}
    </div>
  );
}

export function RecordingOverlay({
  step,
  mediaStream,
  recordingMode,
  reviewBlob,
  error,
  onClose,
}: RecordingOverlayProps) {
  const videoRef = useRef<HTMLVideoElement>(null);
  const recordingAudioSource = useAudioSource(mediaStream ?? null);

  // Set video srcObject for live preview
  useEffect(() => {
    if (videoRef.current && mediaStream && recordingMode === "video") {
      videoRef.current.srcObject = mediaStream;
    }
  }, [mediaStream, recordingMode]);

  // Auto-close after error with a brief delay
  useEffect(() => {
    if (!error) return;
    const timeout = setTimeout(onClose, 1500);
    return () => clearTimeout(timeout);
  }, [error, onClose]);

  const isReviewing = step === "reviewing";
  const isRecording = step === "recording";
  const isLoading = isRecording && !mediaStream;

  return (
    <div className="absolute inset-0 z-50 flex flex-col items-center justify-center bg-black/90">
      {/* Loading state */}
      {isLoading && (
        <div className="z-10 flex flex-col items-center gap-2">
          <span className="animate-pulse text-sm text-white/60">
            {recordingMode === "video"
              ? "Starting camera..."
              : "Starting mic..."}
          </span>
        </div>
      )}

      {/* Camera preview (video mode, recording) */}
      {isRecording && recordingMode === "video" && mediaStream && (
        <video
          ref={videoRef}
          muted
          autoPlay
          playsInline
          className="absolute inset-0 h-full w-full -scale-x-100 object-cover"
        />
      )}

      {/* Review playback */}
      {isReviewing && reviewBlob && (
        <ReviewPlayback
          blob={reviewBlob}
          isVideo={recordingMode === "video"}
        />
      )}

      {/* Top center: recording indicator */}
      <div className="absolute top-8 z-10">
        {isRecording && !isLoading ? (
          <RecordingTimer />
        ) : isReviewing ? (
          <div className="flex items-center gap-2">
            <span className="text-sm text-white/80">Review recording</span>
          </div>
        ) : null}
      </div>

      {/* Bottom center: audio level bars (recording with active stream) */}
      {isRecording && recordingAudioSource && (
        <div className="z-10 absolute bottom-15">
          <AudioLevelBars sourceNode={recordingAudioSource.sourceNode} />
        </div>
      )}

      {/* Bottom center: keyboard hints */}
      {isRecording && !isLoading && (
        <div className="absolute bottom-8 z-10 flex items-center gap-4 text-sm text-white/50">
          <span>
            Release{" "}
            <kbd className="rounded bg-white/10 px-1.5 py-0.5 font-mono text-xs">
              `
            </kbd>{" "}
            to review
          </span>
          <span>
            <kbd className="rounded bg-white/10 px-1.5 py-0.5 font-mono text-xs">
              Q
            </kbd>{" "}
            cancel
          </span>
        </div>
      )}

      {isReviewing && (
        <div className="absolute bottom-8 z-10 flex items-center gap-4 text-sm text-white/50">
          <span>
            <kbd className="rounded bg-white/10 px-1.5 py-0.5 font-mono text-xs">
              Enter
            </kbd>{" "}
            next
          </span>
          <span>
            <kbd className="rounded bg-white/10 px-1.5 py-0.5 font-mono text-xs">
              Q
            </kbd>{" "}
            cancel
          </span>
        </div>
      )}

      {/* Error state */}
      {error && (
        <div className="z-10 text-sm text-red-400">
          {error}
        </div>
      )}
    </div>
  );
}
