'use client';

import React from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { motion, AnimatePresence } from 'framer-motion';
import { FiMaximize2, FiX } from 'react-icons/fi';
import { usePlayerStore } from '@/stores/playerStore';
import VideoPlayer from './VideoPlayer';

export default function GlobalPlayer() {
  const pathname = usePathname();
  const router = useRouter();
  const { activeVideo, isPipActive, isMinimized, closeVideo, maximizeVideo } = usePlayerStore();
  
  // Dragging state ref to prevent click-maximize trigger on drag release
  const isDraggingRef = React.useRef(false);

  // Width state for the mini player (can be resized by dragging borders)
  const [pipWidth, setPipWidth] = React.useState(384); // default width 384px (md)

  // Window size to calculate drag constraints
  const [windowSize, setWindowSize] = React.useState({ width: 1200, height: 800 });

  React.useEffect(() => {
    if (typeof window === 'undefined') return;
    const handleResize = () => {
      setWindowSize({ width: window.innerWidth, height: window.innerHeight });
    };
    handleResize();
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  if (!activeVideo || !isPipActive) return null;

  // Hide mini player if we are currently browsing any full player/detail page, unless it is minimized (animating away)
  const isPlayerPage = pathname.startsWith('/movies/') || pathname.startsWith('/series/') || pathname.startsWith('/tv/');
  if (isPlayerPage && !isMinimized) {
    return null;
  }

  const handleMaximize = () => {
    maximizeVideo();
    // Redirect back to the correct detail page
    if (activeVideo.contentType === 'movie') {
      router.push(`/movies/${activeVideo.contentId}`);
    } else if (activeVideo.contentType === 'series') {
      router.push(`/series/${activeVideo.seriesId || activeVideo.contentId}`);
    } else if (activeVideo.contentType === 'live') {
      router.push(`/tv/${activeVideo.contentId}`);
    }
  };

  const handleContainerClick = (e: React.MouseEvent) => {
    // If the user was dragging the window, do not maximize on release
    if (isDraggingRef.current) return;

    // Only maximize if they didn't click one of the control buttons (close/maximize icon buttons)
    if ((e.target as HTMLElement).closest('button')) return;
    
    // Also ignore clicks on the resize border handles
    if ((e.target as HTMLElement).closest('[data-resize-handle]')) return;

    handleMaximize();
  };

  const handleResizeStart = (e: React.MouseEvent | React.TouchEvent, direction: 'left' | 'top' | 'top-left') => {
    e.preventDefault();
    e.stopPropagation();

    const clientX = 'touches' in e ? e.touches[0].clientX : e.clientX;
    const clientY = 'touches' in e ? e.touches[0].clientY : e.clientY;

    const startX = clientX;
    const startY = clientY;
    const startWidth = pipWidth;

    const handleMouseMove = (moveEvent: MouseEvent | TouchEvent) => {
      const currentX = 'touches' in moveEvent ? moveEvent.touches[0].clientX : moveEvent.clientX;
      const currentY = 'touches' in moveEvent ? moveEvent.touches[0].clientY : moveEvent.clientY;

      let newWidth = startWidth;

      if (direction === 'left') {
        const deltaX = startX - currentX;
        newWidth = startWidth + deltaX;
      } else if (direction === 'top') {
        const deltaY = startY - currentY;
        newWidth = startWidth + (deltaY * 16/9);
      } else if (direction === 'top-left') {
        const deltaX = startX - currentX;
        const deltaY = startY - currentY;
        newWidth = startWidth + Math.max(deltaX, deltaY * 16/9);
      }

      // Constrain width between 240px and 640px
      newWidth = Math.max(240, Math.min(640, newWidth));
      setPipWidth(newWidth);
    };

    const handleMouseUp = () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
      document.removeEventListener('touchmove', handleMouseMove);
      document.removeEventListener('touchend', handleMouseUp);
    };

    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
    document.addEventListener('touchmove', handleMouseMove);
    document.addEventListener('touchend', handleMouseUp);
  };

  const width = pipWidth;
  const height = width * (9/16);

  // Constraints relative to bottom-6 right-6 fixed initial position
  const dragConstraints = {
    left: -windowSize.width + width + 48,
    right: 0,
    top: -windowSize.height + height + 48,
    bottom: 0
  };

  return (
    <AnimatePresence>
      <motion.div 
        initial={{ opacity: 0, scale: 0.9, y: 20 }}
        animate={{ opacity: 1, scale: 1, y: 0 }}
        exit={{ opacity: 0, scale: 0.9, y: 20 }}
        transition={{ type: 'spring', damping: 25, stiffness: 250 }}
        onClick={handleContainerClick}
        drag
        dragConstraints={dragConstraints}
        dragElastic={0.05}
        dragMomentum={false}
        onDragStart={() => {
          isDraggingRef.current = true;
        }}
        onDragEnd={() => {
          setTimeout(() => {
            isDraggingRef.current = false;
          }, 50);
        }}
        style={{ width: pipWidth, height: pipWidth * (9/16) }}
        className="fixed bottom-6 right-6 z-50 rounded-xl overflow-hidden shadow-2xl shadow-black/90 border border-white/10 bg-dark-200 group/pip cursor-grab active:cursor-grabbing select-none"
      >
        {/* Resize border handles */}
        <div 
          data-resize-handle="top"
          onMouseDown={(e) => handleResizeStart(e, 'top')}
          onTouchStart={(e) => handleResizeStart(e, 'top')}
          className="absolute top-0 left-0 right-0 h-[6px] cursor-ns-resize z-[60] bg-transparent hover:bg-primary/45 transition-colors"
          title="Arrastra para redimensionar"
        />
        <div 
          data-resize-handle="left"
          onMouseDown={(e) => handleResizeStart(e, 'left')}
          onTouchStart={(e) => handleResizeStart(e, 'left')}
          className="absolute top-0 bottom-0 left-0 w-[6px] cursor-ew-resize z-[60] bg-transparent hover:bg-primary/45 transition-colors"
          title="Arrastra para redimensionar"
        />
        <div 
          data-resize-handle="top-left"
          onMouseDown={(e) => handleResizeStart(e, 'top-left')}
          onTouchStart={(e) => handleResizeStart(e, 'top-left')}
          className="absolute top-0 left-0 w-[12px] h-[12px] cursor-nwse-resize z-[70] bg-transparent hover:bg-primary transition-colors rounded-br"
          title="Arrastra para redimensionar"
        />

        {/* Simple floating wrapper for the player */}
        <div className="w-full h-full relative pointer-events-none">
          <div className="w-full h-full pointer-events-auto">
            <VideoPlayer
              streamUrl={activeVideo.streamUrl}
              title={activeVideo.title}
              poster={activeVideo.poster}
              contentId={activeVideo.contentId}
              contentType={activeVideo.contentType === 'live' ? 'live' : activeVideo.contentType}
              categoryId={activeVideo.categoryId}
              seriesId={activeVideo.seriesId}
              autoPlay
              isMini
            />
          </div>
 
          {/* Overlay controls visible on hover */}
          <div className="absolute inset-0 bg-black/60 opacity-0 group-hover/pip:opacity-100 transition-opacity flex items-center justify-between p-3 z-30 pointer-events-none">
            <span className="text-[10px] font-bold text-white truncate max-w-[120px] sm:max-w-[160px] shadow-sm select-none">
              {activeVideo.title}
            </span>
            <div className="flex items-center gap-1.5 pointer-events-auto font-sans">
              <button
                onClick={handleMaximize}
                className="p-1.5 rounded-lg bg-black/60 text-white/80 hover:text-white hover:bg-primary transition-all cursor-pointer border-0 flex items-center justify-center"
                title="Maximizar"
              >
                <FiMaximize2 size={13} />
              </button>
              <button
                onClick={closeVideo}
                className="p-1.5 rounded-lg bg-black/60 text-white/80 hover:text-white hover:bg-red-600 transition-all cursor-pointer border-0 flex items-center justify-center"
                title="Cerrar"
              >
                <FiX size={13} />
              </button>
            </div>
          </div>
        </div>
      </motion.div>
    </AnimatePresence>
  );
}
