'use client';

import React from 'react';
import { FiX, FiVolume2, FiVolumeX } from 'react-icons/fi';
import { useMultiStreamStore } from '@/stores/multiStreamStore';
import VideoPlayer from './VideoPlayer';
import { cn } from '@/lib/utils';

export default function MultiStreamPlayer() {
  const {
    streams,
    activeAudioIndex,
    removeStream,
    setActiveAudio,
    resetMultiStream,
  } = useMultiStreamStore();

  if (streams.length === 0) return null;

  // Determine grid layout columns for Mosaic mode
  const getGridLayoutClass = () => {
    if (streams.length === 1) return 'grid-cols-1';
    if (streams.length === 2) return 'grid-cols-2';
    return 'grid-cols-2 grid-rows-2';
  };

  const handleCloseSlot = (index: number) => {
    removeStream(index);
  };

  const handleAudioSelect = (index: number) => {
    setActiveAudio(index);
  };

  return (
    <div className="relative w-full aspect-video bg-neutral-950 rounded-2xl overflow-hidden border border-white/5 shadow-2xl flex flex-col group/multiview select-none">
      
      {/* Mosaic Layout Grid */}
      <div className={cn('grid gap-2 p-2 w-full h-full bg-neutral-900', getGridLayoutClass())}>
        {streams.map((stream, index) => {
          const isAudioActive = index === activeAudioIndex;

          return (
            <div
              key={`${stream.id}-${index}`}
              className={cn(
                'relative overflow-hidden transition-all duration-300 flex flex-col aspect-video bg-black rounded-lg border-2 group/slot',
                // Highlight active audio slot
                isAudioActive ? 'border-primary shadow-lg shadow-primary/10' : 'border-white/5 hover:border-white/20'
              )}
            >
              {/* Video Player */}
              <div className="flex-1 w-full h-full min-h-0 min-w-0">
                <VideoPlayer
                  streamUrl={stream.url}
                  title={stream.title}
                  muted={!isAudioActive}
                  isMultiViewChild={true}
                  poster={stream.posterUrl}
                  contentId={stream.id}
                  contentType={stream.type === 'tv' ? 'live' : stream.type}
                />
              </div>

              {/* Hover Controls Overlay */}
              <div className="absolute inset-x-0 top-0 p-3 bg-gradient-to-b from-black/85 to-transparent flex items-center justify-between opacity-0 group-hover/slot:opacity-100 transition-opacity duration-300 z-10">
                <span className="text-xs font-bold text-white truncate max-w-[55%] bg-black/50 px-2 py-1 rounded pointer-events-auto shadow-md">
                  {stream.title}
                </span>

                <div className="flex items-center gap-1.5 pointer-events-auto">
                  {/* Audio Selector Toggle */}
                  <button
                    onClick={() => handleAudioSelect(index)}
                    className={cn(
                      'p-1.5 rounded-lg border transition-all duration-300',
                      isAudioActive
                        ? 'bg-primary text-white border-primary shadow shadow-primary/20'
                        : 'bg-black/60 text-white/50 border-white/10 hover:text-white hover:bg-white/10'
                    )}
                    title={isAudioActive ? 'Audio Activo' : 'Activar Audio'}
                  >
                    {isAudioActive ? <FiVolume2 size={14} /> : <FiVolumeX size={14} />}
                  </button>

                  {/* Close Stream Slot */}
                  <button
                    onClick={() => handleCloseSlot(index)}
                    className="p-1.5 rounded-lg bg-red-500/20 text-red-500 border border-red-500/30 hover:bg-red-500 hover:text-white transition-all duration-300 shadow"
                    title="Cerrar reproducción"
                  >
                    <FiX size={14} />
                  </button>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Global close toggle bar */}
      <div className="absolute bottom-4 left-1/2 -translate-x-1/2 px-4 py-2 bg-neutral-950/90 backdrop-blur-md rounded-full border border-white/10 flex items-center gap-3 opacity-0 group-hover/multiview:opacity-100 transition-opacity duration-300 z-30 shadow-2xl">
        <span className="text-xs font-semibold text-white/70">
          Modo Multipantalla Mosaico
        </span>
        <div className="w-px h-4 bg-white/10" />
        <button
          onClick={resetMultiStream}
          className="text-xs font-semibold text-red-500 hover:text-red-400 transition-colors"
        >
          Cerrar Multipantalla
        </button>
      </div>

    </div>
  );
}
