import { useEffect, useRef, useState } from "react";
import { Paperclip } from "lucide-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";
import { AttachmentStrip } from "@/features/compose/attachment-strip";
import type { PendingAttachment } from "@/features/compose/attachment-strip";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";

interface RecordingOverlayProps {
  step: "recording" | "reviewing";
  mediaStream: MediaStream | null;
  recordingMode: RecordingMode;
  reviewBlob: Blob | null;
  error: string | null;
  onClose: () => void;
  attachments: PendingAttachment[];
  onRemoveAttachment: (id: string) => void;
  onAddFiles: () => void;
  isDragging: boolean;
  dropZoneProps: {
    onDragOver: (e: React.DragEvent) => void;
    onDragEnter: (e: React.DragEvent) => void;
    onDragLeave: (e: React.DragEvent) => void;
    onDrop: (e: React.DragEvent) => void;
  };
  /** Mirror the video horizontally. Defaults to true (selfie-view for webcam). */
  mirror?: boolean;
  /** How video fills its container. Defaults to "cover". Use "contain" for screen recordings. */
  objectFit?: "cover" | "contain";
}

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,
  mirror = true,
  objectFit = "cover",
}: {
  blob: Blob;
  isVideo: boolean;
  mirror?: boolean;
  objectFit?: "cover" | "contain";
}) {
  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 ${objectFit === "contain" ? "object-contain" : "object-cover"}${mirror ? " -scale-x-100" : ""}`}
      />
    );
  }

  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,
  attachments,
  onRemoveAttachment,
  onAddFiles,
  isDragging,
  dropZoneProps,
  mirror = true,
  objectFit = "cover",
}: 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={cn(
        "absolute inset-0 z-50 flex flex-col items-center justify-center bg-black/90",
        isReviewing && isDragging && "ring-2 ring-inset ring-white/30",
      )}
      {...(isReviewing ? dropZoneProps : {})}
    >
      {/* 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"}
          mirror={mirror}
          objectFit={objectFit}
        />
      )}

      {/* Bottom gradient scrim for keyboard hint readability */}
      {(isRecording || isReviewing) && !isLoading && (
        <div className="pointer-events-none absolute inset-x-0 bottom-0 z-[5] h-1/4 bg-gradient-to-t from-black/60 to-transparent" />
      )}

      {/* 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-4 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-4 z-10 flex flex-col items-center gap-3">
          {attachments.length > 0 && (
            <div className="px-4">
              <AttachmentStrip
                attachments={attachments}
                onRemove={onRemoveAttachment}
                onAddClick={onAddFiles}
              />
            </div>
          )}
          <div className="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>
            <span>
              <Button
                variant="ghost"
                type="button"
                onClick={(e) => {
                  e.stopPropagation();
                  onAddFiles();
                }}
                title="Attach files"
              >
                <Paperclip className="size-4" />
                attach
              </Button>
            </span>

          </div>
        </div>
      )}

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