'use client';

/**
 * HybridSimplePlayer - Easy-to-use hybrid audio player wrapper
 *
 * Combines HybridAudioProvider + HybridAudioPlayer + optional reactive cover
 * in a single component with sensible defaults.
 *
 * Uses native HTML5 audio for playback (no crackling) with Web Audio API
 * for visualization only.
 *
 * @example
 * // Minimal usage
 * <HybridSimplePlayer src="https://example.com/audio.mp3" />
 *
 * @example
 * // With cover art and reactive effects
 * <HybridSimplePlayer
 *   src={audioUrl}
 *   title="Track Title"
 *   artist="Artist Name"
 *   coverArt="/path/to/cover.jpg"
 *   reactiveCover
 *   variant="spotlight"
 * />
 */

import { type ReactNode } from 'react';
import { Music } from 'lucide-react';
import { cn } from '@djangocfg/ui-core';

import { HybridAudioProvider } from '../context/HybridAudioProvider';
import { HybridAudioPlayer } from './HybridAudioPlayer';
import { AudioReactiveCover } from './ReactiveCover';
import { VisualizationProvider, useVisualization } from '../hooks';
import type { EffectIntensity, EffectColorScheme } from '../effects';
import type { VisualizationVariant } from '../hooks';

// =============================================================================
// TYPES
// =============================================================================

export interface HybridSimplePlayerProps {
  /** Audio source URL */
  src: string;

  /** Track title */
  title?: string;

  /** Artist name */
  artist?: string;

  /** Cover art URL or ReactNode */
  coverArt?: string | ReactNode;

  /** Cover art size */
  coverSize?: 'sm' | 'md' | 'lg';

  /** Show frequency waveform */
  showWaveform?: boolean;

  /** Waveform visualization mode */
  waveformMode?: 'frequency' | 'static';

  /** Waveform height in pixels */
  waveformHeight?: number;

  /** Show timer */
  showTimer?: boolean;

  /** Show volume control */
  showVolume?: boolean;

  /** Show loop/repeat button */
  showLoop?: boolean;

  /** Enable audio-reactive cover effects */
  reactiveCover?: boolean;

  /** Reactive effect variant */
  variant?: VisualizationVariant;

  /** Reactive effect intensity */
  intensity?: EffectIntensity;

  /** Reactive effect color scheme */
  colorScheme?: EffectColorScheme;

  /** Auto-play on load */
  autoPlay?: boolean;

  /** Loop playback */
  loop?: boolean;

  /** Initial volume (0-1) */
  initialVolume?: number;

  /** Layout direction */
  layout?: 'vertical' | 'horizontal';

  /** Additional class name */
  className?: string;

  /** Callbacks */
  onPlay?: () => void;
  onPause?: () => void;
  onEnded?: () => void;
  onError?: (error: Error) => void;
}

// =============================================================================
// CONSTANTS
// =============================================================================

const COVER_SIZES = {
  sm: 'w-24 h-24',
  md: 'w-32 h-32',
  lg: 'w-48 h-48',
};

// In horizontal layout cover stays fixed-size; in vertical it fills the full width
const COVER_SIZE_FOR_LAYOUT = (coverSize: 'sm' | 'md' | 'lg', isHorizontal: boolean) =>
  isHorizontal ? coverSize : 'full';

// =============================================================================
// COMPONENT
// =============================================================================

export function HybridSimplePlayer(props: HybridSimplePlayerProps) {
  return (
    <VisualizationProvider>
      <HybridSimplePlayerContent {...props} />
    </VisualizationProvider>
  );
}

function HybridSimplePlayerContent({
  src,
  title,
  artist,
  coverArt,
  coverSize = 'md',
  showWaveform = true,
  waveformMode = 'frequency',
  waveformHeight = 64,
  showTimer = true,
  showVolume = true,
  showLoop = true,
  reactiveCover = true,
  variant,
  intensity,
  colorScheme,
  autoPlay = false,
  loop = false,
  initialVolume = 1,
  layout = 'vertical',
  className,
  onPlay,
  onPause,
  onEnded,
  onError,
}: HybridSimplePlayerProps) {
  const { settings: vizSettings, nextVariant } = useVisualization();

  // Determine effective variant (from props or localStorage settings)
  const effectiveVariant =
    variant ?? (vizSettings.variant !== 'none' ? vizSettings.variant : 'spotlight');
  const effectiveIntensity = intensity ?? vizSettings.intensity;
  const effectiveColorScheme = colorScheme ?? vizSettings.colorScheme;

  // Show reactive cover if enabled and variant is not 'none'
  const showReactiveCover = reactiveCover && effectiveVariant !== 'none';

  // Render cover art content
  const renderCoverContent = () => {
    if (typeof coverArt === 'string') {
      return (
        <img src={coverArt} alt={title || 'Album cover'} className="w-full h-full object-cover" />
      );
    }

    if (coverArt) {
      return coverArt;
    }

    // Default placeholder
    return (
      <div className="w-full h-full bg-muted/30 flex items-center justify-center">
        <Music className="w-1/3 h-1/3 text-muted-foreground/50" />
      </div>
    );
  };

  const isHorizontal = layout === 'horizontal';

  return (
    <HybridAudioProvider
      src={src}
      autoPlay={autoPlay}
      loop={loop}
      initialVolume={initialVolume}
      onPlay={onPlay}
      onPause={onPause}
      onEnded={onEnded}
      onError={onError}
    >
      <div
        className={cn(
          'flex gap-4',
          isHorizontal ? 'flex-row items-center' : 'flex-col items-center',
          className
        )}
      >
        {/* Cover Art */}
        {(coverArt || reactiveCover) && (
          <div className={cn('flex flex-col items-center gap-2', isHorizontal ? 'shrink-0' : 'w-full')}>
            {showReactiveCover ? (
              <AudioReactiveCover
                size={COVER_SIZE_FOR_LAYOUT(coverSize, isHorizontal)}
                variant={effectiveVariant as 'glow' | 'orbs' | 'spotlight' | 'mesh'}
                intensity={effectiveIntensity}
                colorScheme={effectiveColorScheme}
                onClick={nextVariant}
              >
                <div className={cn('rounded-lg overflow-hidden', isHorizontal ? COVER_SIZES[coverSize] : 'w-full h-full')}>
                  {renderCoverContent()}
                </div>
              </AudioReactiveCover>
            ) : (
              <div
                className={cn(
                  'rounded-lg overflow-hidden shadow-lg cursor-pointer',
                  isHorizontal ? COVER_SIZES[coverSize] : 'w-full sm:max-w-xs aspect-square mx-auto'
                )}
                onClick={nextVariant}
                role="button"
                tabIndex={0}
                onKeyDown={(e) => e.key === 'Enter' && nextVariant()}
              >
                {renderCoverContent()}
              </div>
            )}

            {/* Effect indicator */}
            {reactiveCover && (
              <span className="text-[10px] uppercase tracking-wider text-muted-foreground/50 select-none">
                {vizSettings.variant === 'none' ? 'off' : vizSettings.variant}
              </span>
            )}
          </div>
        )}

        {/* Track Info + Player */}
        <div
          className={cn('flex flex-col gap-3', isHorizontal ? 'flex-1 min-w-0' : 'w-full')}
        >
          {/* Track Info */}
          {(title || artist) && (
            <div className={cn('text-center', isHorizontal && 'text-left')}>
              {title && (
                <h3 className="text-base font-medium text-foreground truncate">{title}</h3>
              )}
              {artist && <p className="text-sm text-muted-foreground truncate">{artist}</p>}
            </div>
          )}

          {/* Audio Player */}
          <HybridAudioPlayer
            showControls
            showWaveform={showWaveform}
            waveformMode={waveformMode}
            waveformHeight={waveformHeight}
            showTimer={showTimer}
            showVolume={showVolume}
            showLoop={showLoop}
            className="border-0 bg-transparent"
          />
        </div>
      </div>
    </HybridAudioProvider>
  );
}

export default HybridSimplePlayer;
