'use client';

/**
 * HybridAudioPlayer - Audio playback controls with frequency visualization
 *
 * Uses HybridAudioContext for state management.
 * Native HTML5 audio for playback, Web Audio API for visualization only.
 *
 * Features:
 * - Real-time frequency visualization
 * - Playback controls (play, pause, skip, restart)
 * - Volume control with mute
 * - Loop toggle
 * - Keyboard shortcuts
 * - Timer display
 */

import { memo, useMemo } from 'react';
import {
  Play,
  Pause,
  RotateCcw,
  SkipBack,
  SkipForward,
  Volume2,
  VolumeX,
  Loader2,
  Repeat,
} from 'lucide-react';
import { useAppT } from '@djangocfg/i18n';
import { Button, Slider, cn } from '../../_shared';
import { useHybridAudioContext } from '../context/HybridAudioProvider';
import { HybridWaveform } from './HybridWaveform';
import { formatTime } from '../utils';

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

export interface HybridAudioPlayerProps {
  /** Show playback controls */
  showControls?: boolean;
  /** Show frequency waveform */
  showWaveform?: boolean;
  /** Waveform visualization mode */
  waveformMode?: 'frequency' | 'static';
  /** Waveform height in pixels */
  waveformHeight?: number;
  /** Show time display */
  showTimer?: boolean;
  /** Show volume control */
  showVolume?: boolean;
  /** Show loop button */
  showLoop?: boolean;
  /** Additional CSS class */
  className?: string;
  /** Inline styles */
  style?: React.CSSProperties;
}

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

export const HybridAudioPlayer = memo(function HybridAudioPlayer({
  showControls = true,
  showWaveform = true,
  waveformMode = 'frequency',
  waveformHeight = 64,
  showTimer = true,
  showVolume = true,
  showLoop = true,
  className,
  style,
}: HybridAudioPlayerProps) {
  const t = useAppT();
  const { state, controls } = useHybridAudioContext();

  const labels = useMemo(() => ({
    restart: t('tools.audio.restart'),
    back: t('tools.audio.back'),
    forward: t('tools.audio.forward'),
    volume: t('tools.audio.volume'),
  }), [t]);

  const isLoading = !state.isReady;

  const handleVolumeChange = (value: number[]) => {
    controls.setVolume(value[0] / 100);
  };

  return (
    <div
      className={cn('flex flex-col gap-3 p-4 rounded-lg bg-card border', className)}
      style={style}
    >
      {/* Frequency Waveform */}
      {showWaveform && (
        <div className="relative">
          <HybridWaveform
            mode={waveformMode}
            height={waveformHeight}
            className={cn(isLoading && 'opacity-50')}
          />
          {isLoading && (
            <div className="absolute inset-0 flex items-center justify-center">
              <Loader2 className="h-6 w-6 animate-spin text-primary" />
            </div>
          )}
        </div>
      )}

      {/* Timer */}
      {showTimer && (
        <div className="flex justify-between text-xs text-muted-foreground tabular-nums px-1">
          <span>{formatTime(state.currentTime)}</span>
          <span>{formatTime(state.duration)}</span>
        </div>
      )}

      {/* Controls */}
      {showControls && (
        <div className="flex items-center justify-center gap-1">
          {/* Restart */}
          <Button
            variant="ghost"
            size="icon"
            className="h-9 w-9"
            onClick={controls.restart}
            disabled={!state.isReady}
            title={labels.restart}
          >
            <RotateCcw className="h-4 w-4" />
          </Button>

          {/* Skip back 5s */}
          <Button
            variant="ghost"
            size="icon"
            className="h-9 w-9"
            onClick={() => controls.skip(-5)}
            disabled={!state.isReady}
            title={labels.back}
          >
            <SkipBack className="h-4 w-4" />
          </Button>

          {/* Play/Pause */}
          <Button
            variant="default"
            size="icon"
            className="h-12 w-12 rounded-full"
            onClick={controls.togglePlay}
            disabled={!state.isReady && !isLoading}
            title={state.isPlaying ? 'Pause' : 'Play'}
          >
            {isLoading ? (
              <Loader2 className="h-5 w-5 animate-spin" />
            ) : state.isPlaying ? (
              <Pause className="h-5 w-5" />
            ) : (
              <Play className="h-5 w-5 ml-0.5" />
            )}
          </Button>

          {/* Skip forward 5s */}
          <Button
            variant="ghost"
            size="icon"
            className="h-9 w-9"
            onClick={() => controls.skip(5)}
            disabled={!state.isReady}
            title={labels.forward}
          >
            <SkipForward className="h-4 w-4" />
          </Button>

          {/* Volume */}
          {showVolume && (
            <>
              <Button
                variant="ghost"
                size="icon"
                className="h-9 w-9"
                onClick={controls.toggleMute}
                title={state.isMuted ? 'Unmute' : 'Mute'}
              >
                {state.isMuted || state.volume === 0 ? (
                  <VolumeX className="h-4 w-4" />
                ) : (
                  <Volume2 className="h-4 w-4" />
                )}
              </Button>

              <Slider
                value={[state.isMuted ? 0 : state.volume * 100]}
                max={100}
                step={1}
                onValueChange={handleVolumeChange}
                className="w-20"
                aria-label={labels.volume}
              />
            </>
          )}

          {/* Loop/Repeat */}
          {showLoop && (
            <Button
              variant="ghost"
              size="icon"
              className={cn('h-9 w-9', state.isLooping && 'text-primary')}
              onClick={controls.toggleLoop}
              disabled={!state.isReady}
              title={state.isLooping ? 'Disable loop' : 'Enable loop'}
            >
              <Repeat className="h-4 w-4" />
            </Button>
          )}
        </div>
      )}
    </div>
  );
});

export default HybridAudioPlayer;
