import { useEffect, useRef, useState } from 'react';
import { Paperclip } from 'lucide-react';
import type { RecordingMode } from '@/stores/media-settings-store';
import { CenteredWaveform } from '@/components/audio/centered-waveform';
import { useAudioSource } from '@/components/audio/use-audio-source';
import { useObjectUrl } from '@/hooks/use-object-url';
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';
import { KeyHint } from '@/components/key-hint';
import { useComposeIntentStore } from '@/stores/compose-intent-store';

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 objectUrl = useObjectUrl(blob);
  const [audioEl, setAudioEl] = useState<HTMLAudioElement | null>(null);
  const audioSource = useAudioSource(isVideo ? null : audioEl);

  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={setAudioEl} src={objectUrl} autoPlay loop />
      {audioSource ? (
        <CenteredWaveform
          sourceNode={audioSource.sourceNode}
          className="text-white"
        />
      ) : (
        <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;
  const requestIntent = useComposeIntentStore((s) => s.request);

  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: live waveform (recording with active stream) */}
      {isRecording && recordingAudioSource && (
        <div className="z-10 absolute bottom-15">
          <CenteredWaveform
            sourceNode={recordingAudioSource.sourceNode}
            className="text-white"
          />
        </div>
      )}

      {/* Bottom center: keyboard hints */}
      {isRecording && !isLoading && (
        <div className="absolute bottom-4 z-10 flex items-center gap-4 text-sm text-white/50">
          <KeyHint
            keys="`"
            prefix="Release"
            onClick={() => requestIntent('stop')}
            title="Finish recording (or release `)"
          >
            to review
          </KeyHint>
          <KeyHint
            keys={['Esc', 'Q']}
            separator="or"
            onClick={() => requestIntent('cancel')}
            title="Discard recording (or press Esc / Q)"
          >
            to cancel
          </KeyHint>
        </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">
            <KeyHint
              keys="Enter"
              onClick={() => requestIntent('send')}
              title="Send (or press Enter)"
            >
              next
            </KeyHint>
            <KeyHint
              keys={['Esc', 'Q']}
              separator="or"
              onClick={() => requestIntent('cancel')}
              title="Discard (or press Esc / Q)"
            >
              to cancel
            </KeyHint>
            <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>
  );
}
