import React from 'react';
import { useTranslation } from 'react-i18next';
import { createPortal } from 'react-dom';
import {
  Play,
  Pause,
  Volume2,
  VolumeX,
  Maximize2,
  PlayCircle,
  PauseCircle,
  RotateCcw,
  Gauge,
  Info,
  Download,
  X,
  ExternalLink,
  Radio,
  MoreVertical,
  MoreHorizontal,
} from 'lucide-react';
import { Slider } from '../../ui/slider';
import { Button } from '../../ui/button';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../../ui/tooltip';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
} from '../../ui/dropdown-menu';
import { FloatingMediaWrapper } from '../FloatingMediaWrapper';
import { cn } from '../../shared/utils';
import { useAudioPlayer } from './use-audio-player';

export interface AudioPlayerProps {
  /** Source URL of the audio file */
  src?: string;
  /** Title of the audio track/podcast */
  title?: string;
  /** Artist or subtitle information */
  artist?: string;
  /** Subtitle or source information (specific to 'bar' variant) */
  subtitle?: string;
  /** URL for cover art (specific to 'card' variant) */
  coverArt?: string;
  /** Whether to play automatically */
  autoPlay?: boolean;
  /** CSS class name for the container */
  className?: string;
  /** Display variant: 'card' (standard floating) or 'bar' (global fixed bar) */
  variant?: 'card' | 'bar';
  /** Whether the player is currently visible and open (only for 'bar' variant) */
  isOpen?: boolean;
  /** Callback to close the player bar (only for 'bar' variant) */
  onClose?: () => void;
  /** Total duration in seconds (optional, will be loaded from metadata if not provided) */
  duration?: number;
  /** Initial playback time in seconds */
  currentTime?: number;
  /** Color theme variant for the bar layout */
  colorVariant?: 'default' | 'primary';
  /** Whether the player should automatically float when scrolled out of view */
  enableAutoFloat?: boolean;
  /** Callback fired when user manually closes the floating player */
  onCloseFloating?: () => void;
}

/**
 * Unified Audio Player component.
 *
 * All state and logic is managed by the `useAudioPlayer` headless hook.
 * This component is responsible only for rendering.
 */
export function AudioPlayer({
  src,
  title,
  artist,
  subtitle,
  autoPlay = false,
  className,
  variant = 'card',
  isOpen = true,
  onClose,
  duration: initialDuration,
  currentTime: initialTime = 0,
  colorVariant = 'default',
  enableAutoFloat = true,
  onCloseFloating,
}: AudioPlayerProps) {
  const { t } = useTranslation();

  const {
    audioRef,
    containerRef,
    isPlaying,
    currentTime,
    duration,
    volume,
    isMuted,
    playbackSpeed,
    isFloating,
    isManualFloating,
    isVisible,
    isMobile,
    enableAutoFloatLocal,
    sidebarExpanded,
    sidebarWidth,
    assistenteExpanded,
    togglePlay,
    toggleMute,
    handleSeek,
    handleVolumeChange,
    handleSetFloating,
    handleEnableManualFloat,
    setPlaybackSpeed,
    resetAudio,
    formatTime,
    onPlay,
    onPause,
    onEnded,
    onTimeUpdate,
    onLoadedMetadata,
  } = useAudioPlayer({
    src,
    autoPlay,
    initialTime,
    initialDuration,
    variant,
    isOpen,
    enableAutoFloat,
    onCloseFloating,
  });

  // ── Audio element (hidden) ──────────────────────────────────────────────────
  const audioElement = (
    <audio
      ref={audioRef}
      src={src}
      autoPlay={autoPlay}
      className="hidden"
      onTimeUpdate={onTimeUpdate}
      onLoadedMetadata={onLoadedMetadata}
      onPlay={onPlay}
      onPause={onPause}
      onEnded={onEnded}
    />
  );

  // ── Bar variant — desktop layout ────────────────────────────────────────────
  const desktopLayout = (
    <div
      className={cn(
        'px-6 flex items-center justify-between gap-4',
        colorVariant === 'primary' ? 'h-[80px] gap-6' : 'h-[80px]'
      )}
    >
      {/* Left: Info */}
      <div
        className={cn(
          'flex flex-col min-w-0 shrink-0 relative z-10',
          colorVariant === 'primary' ? 'w-[280px]' : 'w-[280px]'
        )}
      >
        <div className="flex items-center gap-2 mb-0.5">
          {colorVariant === 'primary' ? (
            <div className="w-2 h-2 rounded-full bg-[var(--chart-4)] animate-pulse shrink-0" />
          ) : (
            <Radio className="w-3 h-3 text-[var(--chart-4)] animate-pulse shrink-0" />
          )}
          <h4
            className={cn(
              'truncate',
              colorVariant === 'primary'
                ? 'font-semibold text-base tracking-tight'
                : 'font-medium text-base'
            )}
            title={title || t('media.audioTitle')}
          >
            {title || t('media.audioTitle')}
          </h4>
        </div>
        <div
          className={cn(
            'flex items-center gap-1 text-xs text-muted-foreground',
            colorVariant === 'primary' && 'opacity-80'
          )}
        >
          <span className="truncate">{subtitle || artist}</span>
          <ExternalLink
            className={cn(
              'w-3 h-3 cursor-pointer hover:text-foreground ml-1 transition-opacity',
              colorVariant === 'primary'
                ? 'opacity-60 hover:opacity-100'
                : 'opacity-70 hover:opacity-100'
            )}
          />
        </div>
      </div>

      {/* Center: Controls */}
      <div
        className={cn(
          'flex-1 flex items-center justify-center gap-4 min-w-0 max-w-xl relative z-10',
          colorVariant === 'primary' && 'gap-4'
        )}
      >
        <button
          onClick={togglePlay}
          aria-label={isPlaying ? t('media.pause') : t('media.play')}
          className={cn(
            'transition-all focus:outline-none shrink-0',
            colorVariant === 'primary'
              ? 'hover:scale-110'
              : 'text-muted-foreground hover:text-foreground hover:scale-110 active:scale-95 transform duration-100'
          )}
        >
          {isPlaying ? (
            <PauseCircle
              className={cn(colorVariant === 'primary' ? 'w-12 h-12' : 'w-10 h-10')}
              strokeWidth={colorVariant === 'primary' ? 1 : 1.5}
            />
          ) : (
            <PlayCircle
              className={cn(colorVariant === 'primary' ? 'w-12 h-12' : 'w-10 h-10')}
              strokeWidth={colorVariant === 'primary' ? 1 : 1.5}
            />
          )}
        </button>

        <div className="flex-1 flex items-center gap-3 max-w-lg">
          <span
            className={cn(
              'text-xs font-mono shrink-0 w-10 text-right',
              colorVariant === 'primary' ? 'text-[11px] w-12 opacity-80' : 'text-muted-foreground'
            )}
          >
            {formatTime(currentTime)}
          </span>
          <Slider
            value={[currentTime]}
            max={duration || 100}
            onValueChange={handleSeek}
            className="cursor-pointer"
          />
          <span
            className={cn(
              'text-xs font-mono shrink-0 w-10',
              colorVariant === 'primary' ? 'text-[11px] w-12 opacity-80' : 'text-muted-foreground'
            )}
          >
            {formatTime(duration)}
          </span>
        </div>
      </div>

      {/* Right: Actions */}
      <div className="flex items-center gap-2 shrink-0 relative z-10">
        <div className="hidden lg:flex items-center gap-2 w-28 mr-2 group">
          <button
            onClick={toggleMute}
            className="text-muted-foreground hover:text-foreground"
            aria-label={isMuted || volume === 0 ? t('media.unmute') : t('media.mute')}
          >
            {isMuted || volume === 0 ? (
              <VolumeX className="w-5 h-5" />
            ) : (
              <Volume2 className="w-5 h-5" />
            )}
          </button>
          <Slider
            value={[isMuted ? 0 : volume * 100]}
            max={100}
            onValueChange={val => handleVolumeChange([val[0] / 100])}
            className="w-full opacity-60 group-hover:opacity-100 transition-opacity"
          />
        </div>

        <div className="flex items-center gap-1">
          <div className="hidden md:flex">
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="rounded-full h-9 w-9"
                    onClick={resetAudio}
                    aria-label={t('media.restart')}
                  >
                    <RotateCcw className="w-4 h-4" />
                  </Button>
                </TooltipTrigger>
                <TooltipContent className="z-[1001]">{t('media.restart')}</TooltipContent>
              </Tooltip>
            </TooltipProvider>

            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="text-[var(--chart-3)] hover:bg-accent rounded-full h-9 w-9"
                    aria-label={t('media.audioInfo')}
                  >
                    <Info className="w-4 h-4 fill-current" />
                  </Button>
                </TooltipTrigger>
                <TooltipContent className="z-[1001]">{t('media.info')}</TooltipContent>
              </Tooltip>
            </TooltipProvider>
          </div>

          <div className="hidden xl:flex items-center gap-1">
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button
                  variant="ghost"
                  size="icon"
                  className="rounded-full h-9 w-9"
                  aria-label={t('media.selectSpeed')}
                >
                  <Gauge className="w-4 h-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="center" className="w-32 z-[1001]">
                {[0.5, 1, 1.5, 2].map(speed => (
                  <DropdownMenuItem
                    key={speed}
                    onClick={() => setPlaybackSpeed(speed)}
                    className={cn(
                      'cursor-pointer',
                      playbackSpeed === speed && 'bg-accent font-bold'
                    )}
                  >
                    {speed}x
                  </DropdownMenuItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>

            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="rounded-full h-9 w-9"
                    aria-label={t('media.downloadAudio')}
                  >
                    <Download className="w-4 h-4" />
                  </Button>
                </TooltipTrigger>
                <TooltipContent className="z-[1001]">{t('media.downloadAudio')}</TooltipContent>
              </Tooltip>
            </TooltipProvider>
          </div>

          <div className="xl:hidden">
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button
                  variant="ghost"
                  size="icon"
                  className="rounded-full h-9 w-9"
                  aria-label={t('media.moreOptions')}
                >
                  <MoreHorizontal className="w-5 h-5" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-56 p-2 z-[1001]">
                <div className="lg:hidden">
                  <div className="px-2 py-3">
                    <div className="flex items-center justify-between mb-3 px-1">
                      <div className="flex items-center gap-2">
                        {isMuted || volume === 0 ? (
                          <VolumeX className="w-4 h-4 text-muted-foreground" />
                        ) : (
                          <Volume2 className="w-4 h-4 text-muted-foreground" />
                        )}
                        <span className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground/70">
                          Volume
                        </span>
                      </div>
                    </div>
                    <Slider
                      value={[isMuted ? 0 : volume * 100]}
                      max={100}
                      onValueChange={val => handleVolumeChange([val[0] / 100])}
                    />
                  </div>
                  <DropdownMenuSeparator className="my-1" />
                </div>

                <div className="md:hidden">
                  <DropdownMenuItem onClick={resetAudio} className="cursor-pointer py-2.5">
                    <RotateCcw className="w-4 h-4 mr-3 text-muted-foreground" />{' '}
                    {t('media.restart')}
                  </DropdownMenuItem>
                  <DropdownMenuItem className="cursor-pointer py-2.5">
                    <Info className="w-4 h-4 mr-3 text-muted-foreground" /> {t('media.info')}
                  </DropdownMenuItem>
                  <DropdownMenuSeparator className="my-1" />
                </div>

                <div className="xl:hidden">
                  <div className="px-3 py-2 flex flex-col gap-2">
                    <div className="flex items-center gap-2">
                      <Gauge className="w-4 h-4 text-muted-foreground" />
                      <span className="text-sm font-medium">{t('media.speed')}</span>
                    </div>
                    <div className="flex flex-wrap gap-1">
                      {[0.5, 1, 1.5, 2].map(speed => (
                        <button
                          key={speed}
                          onClick={() => setPlaybackSpeed(speed)}
                          className={cn(
                            'px-2 py-0.5 text-[10px] rounded border transition-colors',
                            playbackSpeed === speed
                              ? 'bg-primary text-primary-foreground border-primary'
                              : 'bg-transparent border-border hover:bg-accent'
                          )}
                        >
                          {speed}x
                        </button>
                      ))}
                    </div>
                  </div>
                  <DropdownMenuSeparator className="my-1" />
                  <DropdownMenuItem className="cursor-pointer py-2.5">
                    <Download className="w-4 h-4 mr-3 text-muted-foreground" />{' '}
                    {t('media.downloadAudio')}
                  </DropdownMenuItem>
                </div>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>

          <div className="w-px h-8 bg-border mx-1" />

          <Button
            onClick={onClose}
            variant="ghost"
            size="icon"
            className="rounded-full h-9 w-9"
            aria-label={t('media.closePlayer')}
          >
            <X className="w-5 h-5" />
          </Button>
        </div>
      </div>
    </div>
  );

  // ── Bar variant — mobile layout ─────────────────────────────────────────────
  const mobileLayout = (
    <div
      className={cn(
        'flex flex-col py-3 px-4 gap-3',
        colorVariant === 'primary' && 'py-4 px-5 gap-4'
      )}
    >
      <div className="flex items-start justify-between gap-3">
        <div className="flex flex-col min-w-0 flex-1">
          <div className="flex items-center gap-2 mb-1">
            {colorVariant === 'primary' ? (
              <div className="w-2 h-2 rounded-full bg-[var(--chart-4)] animate-pulse shrink-0" />
            ) : (
              <Radio className="w-3 h-3 text-[var(--chart-4)] animate-pulse shrink-0" />
            )}
            <h4
              className={cn(
                'truncate',
                colorVariant === 'primary'
                  ? 'font-semibold text-sm tracking-tight'
                  : 'font-medium text-sm'
              )}
            >
              {title}
            </h4>
          </div>
          <div
            className={cn(
              'flex items-center gap-1.5 text-xs text-muted-foreground',
              colorVariant === 'primary' && 'opacity-70'
            )}
          >
            <span className="truncate">{subtitle || artist}</span>
          </div>
        </div>
        <Button
          onClick={onClose}
          variant="ghost"
          size="icon"
          className="rounded-full h-8 w-8 shrink-0"
          aria-label={t('media.closePlayer')}
        >
          <X className="w-4 h-4" />
        </Button>
      </div>

      <div className="flex items-center gap-3">
        <button
          onClick={togglePlay}
          aria-label={isPlaying ? t('media.pause') : t('media.play')}
          className="shrink-0 transition-transform active:scale-95"
        >
          {isPlaying ? (
            <PauseCircle
              className={cn(colorVariant === 'primary' ? 'w-12 h-12' : 'w-10 h-10')}
              strokeWidth={colorVariant === 'primary' ? 1 : 1.5}
            />
          ) : (
            <PlayCircle
              className={cn(colorVariant === 'primary' ? 'w-12 h-12' : 'w-10 h-10')}
              strokeWidth={colorVariant === 'primary' ? 1 : 1.5}
            />
          )}
        </button>

        <div className="flex-1 flex items-center gap-2">
          <Slider
            value={[currentTime]}
            max={duration || 100}
            onValueChange={handleSeek}
            className="cursor-pointer"
            aria-label={t('media.playbackProgress')}
          />
        </div>

        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              variant="ghost"
              size="icon"
              className="h-9 w-9 rounded-full"
              aria-label={t('media.moreOptions')}
            >
              <MoreVertical className="w-5 h-5" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="w-56 p-2 z-[1001]">
            <DropdownMenuItem onClick={resetAudio}>{t('media.restart')}</DropdownMenuItem>
            <DropdownMenuItem>{t('media.speedLabel', { speed: playbackSpeed })}</DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
    </div>
  );

  // ── Card variant — compact layout ───────────────────────────────────────────
  const desktopLayoutCompact = (
    <div
      className={cn(
        'flex items-center gap-3 w-full',
        isFloating ? 'px-3 py-1 text-foreground' : 'px-4 py-3'
      )}
    >
      <Button
        onClick={togglePlay}
        size="icon"
        variant="outline"
        className={cn(
          'shrink-0 rounded-full border-border text-foreground hover:bg-accent transition-colors',
          colorVariant === 'primary' &&
            'border-primary-foreground/20 hover:bg-primary-foreground/10 text-primary-foreground',
          isFloating ? 'h-8 w-8' : 'h-10 w-10'
        )}
        aria-label={isPlaying ? t('media.pause') : t('media.play')}
      >
        {isPlaying ? (
          <Pause className={cn(isFloating ? 'w-3 h-3' : 'w-4 h-4', 'fill-current')} />
        ) : (
          <Play className={cn(isFloating ? 'w-3 h-3' : 'w-4 h-4', 'fill-current ml-0.5')} />
        )}
      </Button>
      <div className="flex-1 min-w-0 flex flex-col justify-center gap-1.5">
        <div className="flex items-center justify-between text-xs leading-none">
          <span
            className={cn(
              'font-medium truncate',
              colorVariant === 'primary' ? 'text-primary-foreground' : 'text-foreground'
            )}
          >
            {title}
          </span>
          <span
            className={cn(
              'font-medium tabular-nums text-[10px] sm:text-xs',
              colorVariant === 'primary' ? 'text-primary-foreground/70' : 'text-muted-foreground'
            )}
          >
            {formatTime(currentTime)} / {formatTime(duration)}
          </span>
        </div>
        <Slider
          value={[currentTime]}
          max={duration || 100}
          step={1}
          onValueChange={handleSeek}
          className="w-full"
          aria-label={t('media.playbackProgress')}
        />
      </div>

      <div className="flex items-center gap-1 shrink-0">
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              variant="ghost"
              size="icon"
              className={cn(
                'rounded-full',
                colorVariant === 'primary'
                  ? 'text-primary-foreground/80 hover:text-primary-foreground hover:bg-primary-foreground/10'
                  : 'text-muted-foreground hover:text-foreground',
                isFloating ? 'h-7 w-7' : 'h-8 w-8'
              )}
              aria-label="Mais opções"
            >
              <MoreVertical className={isFloating ? 'w-4 h-4' : 'w-5 h-5'} />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="w-56 p-2 z-[1001]">
            <div className="px-2 py-3">
              <div className="flex items-center justify-between mb-3 px-1">
                <div className="flex items-center gap-2">
                  {isMuted || volume === 0 ? (
                    <VolumeX className="w-4 h-4 text-muted-foreground" />
                  ) : (
                    <Volume2 className="w-4 h-4 text-muted-foreground" />
                  )}
                  <span className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground/70">
                    Volume
                  </span>
                </div>
              </div>
              <Slider
                value={[isMuted ? 0 : volume * 100]}
                max={100}
                onValueChange={val => handleVolumeChange([val[0] / 100])}
                aria-label="Volume"
              />
            </div>

            <DropdownMenuSeparator className="my-2" />

            <div className="px-2 py-1 flex flex-col gap-2">
              <div className="flex items-center gap-2">
                <Gauge className="w-4 h-4 text-muted-foreground" />
                <span className="text-sm font-medium">{t('media.speed')}</span>
              </div>
              <div className="flex flex-wrap gap-1">
                {[0.5, 1, 1.5, 2].map(speed => (
                  <button
                    key={speed}
                    onClick={() => setPlaybackSpeed(speed)}
                    className={cn(
                      'px-2 py-1 text-[10px] rounded border transition-colors',
                      playbackSpeed === speed
                        ? 'bg-primary text-primary-foreground border-primary'
                        : 'bg-transparent border-border hover:bg-accent'
                    )}
                  >
                    {speed}x
                  </button>
                ))}
              </div>
            </div>

            <DropdownMenuSeparator className="my-2" />

            <DropdownMenuItem onClick={resetAudio} className="cursor-pointer py-2.5">
              <RotateCcw className="w-4 h-4 mr-3 text-muted-foreground" />
              <span className="text-sm">{t('media.restart')}</span>
            </DropdownMenuItem>

            <DropdownMenuItem className="cursor-pointer py-2.5">
              <Download className="w-4 h-4 mr-3 text-muted-foreground" />
              <span className="text-sm">{t('media.downloadFile')}</span>
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>

        {!isFloating && (
          <Button
            variant="ghost"
            size="icon"
            className={cn(
              'h-8 w-8',
              colorVariant === 'primary'
                ? 'text-primary-foreground/80 hover:text-primary-foreground hover:bg-primary-foreground/10'
                : 'text-muted-foreground hover:text-foreground'
            )}
            onClick={handleEnableManualFloat}
            title={t('media.floatingMode')}
            aria-label={t('media.openFloatingMode')}
          >
            <Maximize2 className="w-4 h-4" />
          </Button>
        )}
      </div>
    </div>
  );

  // ── Early return ────────────────────────────────────────────────────────────
  if (!isVisible) return null;

  // ── Bar variant — portal render ─────────────────────────────────────────────
  if (variant === 'bar' && isVisible && typeof document !== 'undefined') {
    return createPortal(
      <div
        className={cn(
          'fixed bottom-0 z-[100] border-t transition-all duration-300 ease-in-out',
          colorVariant === 'primary'
            ? 'bg-primary/95 text-primary-foreground border-primary/20 backdrop-blur-sm [&_.text-muted-foreground]:text-primary-foreground/70 [&_.text-foreground]:text-primary-foreground [&_button]:text-primary-foreground [&_[data-slot=slider-track]]:bg-primary-foreground/30 [&_[data-slot=slider-range]]:bg-primary-foreground [&_[data-slot=slider-thumb]]:border-primary-foreground [&_[data-slot=slider-thumb]]:bg-primary-foreground'
            : 'bg-card/95 text-card-foreground border-border backdrop-blur-md shadow-[var(--elevation-sm)]',
          isOpen ? 'translate-y-0 opacity-100' : 'translate-y-full opacity-0',
          className
        )}
        style={{
          left: isMobile ? 0 : sidebarExpanded ? sidebarWidth : 80,
          right: isMobile ? 0 : assistenteExpanded ? 420 : 80,
        }}
      >
        {audioElement}
        {!isMobile ? desktopLayout : mobileLayout}
      </div>,
      document.body
    );
  }

  // ── Card variant — floating wrapper render ──────────────────────────────────
  return (
    <div ref={containerRef} className={className}>
      {audioElement}
      <FloatingMediaWrapper
        isFloating={isFloating}
        setIsFloating={handleSetFloating}
        onClose={() => handleSetFloating(false)}
        onCloseMedia={() => {
          handleSetFloating(false);
        }}
        title={t('media.playingMedia')}
        aspectRatio={320 / 110}
        minHeight={110}
        minWidth={320}
        colorVariant={colorVariant}
        className="w-full"
        playerId="audio-player"
        enablePadding
      >
        <div
          className={cn(
            'w-full overflow-hidden flex flex-col justify-center',
            colorVariant === 'primary'
              ? 'bg-primary text-primary-foreground [&_[data-slot=slider-track]]:bg-white/20 [&_[data-slot=slider-range]]:bg-white [&_[data-slot=slider-thumb]]:border-white [&_[data-slot=slider-thumb]]:bg-white'
              : 'bg-card text-card-foreground',
            isFloating ? 'h-full bg-transparent' : 'border rounded-md shadow-sm'
          )}
        >
          {desktopLayoutCompact}
        </div>
      </FloatingMediaWrapper>
    </div>
  );
}
