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 {
  RECORDING_MAX_DURATION_SECONDS,
  RECORDING_WARNING_SECONDS,
} from '@/lib/constants';
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';
}

const WARNING_AT_SECONDS =
  RECORDING_MAX_DURATION_SECONDS - RECORDING_WARNING_SECONDS;

/**
 * Tracks elapsed recording time and drives the time-limit UI. Keeps the
 * recorder itself unaware of limits: when the cap is reached it dispatches the
 * standard `stop` intent (the same path as releasing the ` key), which finishes
 * the recording into the review step.
 */
function useRecordingCountdown(active: boolean) {
  const [elapsed, setElapsed] = useState(0);
  const requestIntent = useComposeIntentStore((s) => s.request);

  useEffect(() => {
    if (!active) return;

    const start = Date.now();
    let stopped = false;
    // Tick faster than 1s so the auto-stop lands within ~250ms of the cap, but
    // only re-render when the whole-second value actually changes.
    const interval = setInterval(() => {
      const seconds = Math.floor((Date.now() - start) / 1000);
      setElapsed((prev) => (prev === seconds ? prev : seconds));
      if (seconds >= RECORDING_MAX_DURATION_SECONDS && !stopped) {
        stopped = true;
        requestIntent('stop');
      }
    }, 250);
    return () => {
      clearInterval(interval);
      setElapsed(0);
    };
  }, [active, requestIntent]);

  return { elapsed, isWarning: elapsed >= WARNING_AT_SECONDS };
}

function RecordingTimer({
  elapsed,
  isWarning,
}: {
  elapsed: number;
  isWarning: boolean;
}) {
  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={cn(
          'font-mono text-sm text-white/80',
          isWarning && 'text-red-400',
        )}
      >
        {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);

  const { elapsed, isWarning } = useRecordingCountdown(
    isRecording && !isLoading,
  );

  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',
        isRecording && isWarning && 'record-warning-glow',
      )}
      {...(isReviewing ? dropZoneProps : {})}
    >
      {/* Top progress bar: fills over the recording duration, red in warning */}
      {isRecording && !isLoading && (
        <div className="absolute inset-x-0 top-0 z-20 h-1 bg-white/10">
          <div
            className={cn(
              'h-full w-full origin-left record-progress',
              isWarning ? 'bg-red-500' : 'bg-white/80',
            )}
            style={{ animationDuration: `${RECORDING_MAX_DURATION_SECONDS}s` }}
          />
        </div>
      )}
      {/* 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 elapsed={elapsed} isWarning={isWarning} />
        ) : 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>
  );
}
