import { useRef, useState, useEffect } from 'react';
import { Button, Space, Tag, Grid, theme } from 'antd';
import {
  CloseOutlined,
  LikeOutlined,
  LikeFilled,
  EyeOutlined,
  CommentOutlined,
  OrderedListOutlined,
} from '@ant-design/icons';
import { useExpandedVideo, type VideoData } from '@/contexts/ExpandedVideoContext';
import { MediaAuthProvider } from '@/contexts/MediaAuthContext';
import { useAuthStore } from '@/stores/auth.store';
import VideoPlayer, { VideoPlayerRef } from './VideoPlayer';
import LiveChat from './LiveChat';
import ProgressBarMarkers from './ProgressBarMarkers';
import ReactionButtons from './ReactionButtons';
import AddToPlaylistModal from './AddToPlaylistModal';
import { mediaPublicApi } from '@/lib/media-public-api';
import { useKeyboardShortcuts } from '@/hooks/useKeyboardShortcuts';
import axios from 'axios';

const { useBreakpoint } = Grid;

interface ExpandedVideoCardProps {
  video: VideoData;
}

export default function ExpandedVideoCard({ video }: ExpandedVideoCardProps) {
  const { token } = theme.useToken();
  const screens = useBreakpoint();
  const isMobile = !screens.md;
  const { collapseVideo } = useExpandedVideo();

  const containerRef = useRef<HTMLDivElement>(null);
  const videoContainerRef = useRef<HTMLDivElement>(null);
  const playerRef = useRef<VideoPlayerRef | null>(null);
  const [hasUpvoted, setHasUpvoted] = useState(false);
  const [upvoteCount, setUpvoteCount] = useState(video.upvoteCount);
  const [upvoting, setUpvoting] = useState(false);
  const [isMobileChatOpen, setIsMobileChatOpen] = useState(false);
  const [addToPlaylistOpen, setAddToPlaylistOpen] = useState(false);
  const [videoHeight, setVideoHeight] = useState<number>(0);
  const [currentTime, setCurrentTime] = useState(0);
  const [isExpanding, setIsExpanding] = useState(true);
  const isAuthenticated = useAuthStore((s) => s.isAuthenticated);

  // Parent padding to break out of (matches MediaPublicLayout)
  const pad = isMobile ? 8 : 12;

  // Use video title if available, fall back to filename without extension
  const title = video.title || video.filename.replace(/\.[^/.]+$/, '');

  // Keyboard shortcuts
  useKeyboardShortcuts({
    playerRef: playerRef as React.RefObject<VideoPlayerRef>,
    onClose: collapseVideo,
    enabled: !isExpanding,
  });

  // Trigger expand animation after mount
  useEffect(() => {
    const timer = requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        setIsExpanding(false);
      });
    });
    return () => cancelAnimationFrame(timer);
  }, []);

  // Scroll the expanded card into view smoothly
  useEffect(() => {
    const timer = setTimeout(() => {
      if (containerRef.current) {
        containerRef.current.scrollIntoView({
          behavior: isMobile ? 'auto' : 'smooth',
          block: 'nearest',
        });
      }
    }, 350);
    return () => clearTimeout(timer);
  }, [isMobile]);

  // Track video container height for chat sizing
  useEffect(() => {
    const videoContainer = videoContainerRef.current;
    if (!videoContainer) return;

    const updateHeight = () => {
      const height = videoContainer.offsetHeight;
      if (height > 0) setVideoHeight(height);
    };

    const timer = setTimeout(updateHeight, 350);
    const resizeObserver = new ResizeObserver(updateHeight);
    resizeObserver.observe(videoContainer);

    return () => {
      clearTimeout(timer);
      resizeObserver.disconnect();
    };
  }, [isExpanding]);

  // Poll currentTime for ReactionButtons
  useEffect(() => {
    if (isExpanding) return;
    const interval = setInterval(() => {
      const el = playerRef.current?.getVideoElement();
      if (el) setCurrentTime(el.currentTime);
    }, 1000);
    return () => clearInterval(interval);
  }, [isExpanding]);

  const handleUpvote = async () => {
    if (upvoting || hasUpvoted) return;
    try {
      setUpvoting(true);
      await mediaPublicApi.post(`/public/${video.id}/upvote`);
      setHasUpvoted(true);
      setUpvoteCount(prev => prev + 1);
    } catch (error: unknown) {
      console.error('Upvote failed:', error);
      if (axios.isAxiosError(error) && error.response?.status === 401) {
        alert('Please log in to upvote videos');
      }
    } finally {
      setUpvoting(false);
    }
  };

  const formatDuration = (seconds: number | null) => {
    if (!seconds) return '';
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  const formatCount = (count: number) => {
    if (count >= 1000000) return `${(count / 1000000).toFixed(1)}M`;
    if (count >= 1000) return `${(count / 1000).toFixed(1)}K`;
    return count.toString();
  };

  return (
    <div
      ref={containerRef}
      style={{
        gridColumn: '1 / -1',
        background: token.colorBgContainer,
        borderRadius: 0,
        overflow: 'hidden',
        transition: 'opacity 300ms ease-out, max-height 300ms ease-out',
        maxHeight: isExpanding ? 0 : 3000,
        opacity: isExpanding ? 0 : 1,
        // Break out of parent padding to fill full content area
        marginLeft: -pad,
        marginRight: -pad,
        width: `calc(100% + ${pad * 2}px)`,
      }}
    >
      {/* Main content: video (left) + chat (right) */}
      <div
        style={{
          display: 'flex',
          flexDirection: isMobile ? 'column' : 'row',
        }}
      >
        {/* Video section */}
        <div style={{ flex: 1, minWidth: 0 }}>
          {/* Video player */}
          <div
            ref={videoContainerRef}
            style={{
              position: 'relative',
              width: '100%',
              aspectRatio: video.orientation === 'V' ? '9/16' : '16/9',
              // Cap height so player controls stay above the info bar
              maxHeight: isMobile ? 'calc(100vh - 100px)' : 'calc(100vh - 50px)',
              background: '#000',
            }}
          >
            <VideoPlayer
              ref={playerRef}
              videoId={video.id}
              width="100%"
              height="100%"
              autoplay={!isExpanding}
              controls={true}
            />

            {/* Progress Bar Reaction Markers */}
            {video.durationSeconds && playerRef.current?.getVideoElement() && (
              <ProgressBarMarkers
                videoId={video.id}
                durationSeconds={video.durationSeconds}
                playerRef={{ current: playerRef.current.getVideoElement()! }}
              />
            )}
          </div>
        </div>

        {/* Chat panel (desktop only, beside video) */}
        {!isMobile && (
          <div
            style={{
              width: 280,
              flexShrink: 0,
              display: 'flex',
              flexDirection: 'column',
              borderLeft: `1px solid ${token.colorBorder}`,
              background: token.colorBgElevated,
              height: videoHeight > 0 ? videoHeight : 'auto',
              maxHeight: videoHeight > 0 ? videoHeight : 600,
            }}
          >
            <MediaAuthProvider>
              <LiveChat
                videoId={video.id}
                isOpen={true}
                onRequestLogin={() => {}}
              />
            </MediaAuthProvider>
          </div>
        )}
      </div>

      {/* Bottom info bar */}
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: 6,
          padding: isMobile ? '6px 12px' : '6px 16px',
          borderTop: `1px solid ${token.colorBorder}`,
          flexWrap: 'wrap',
        }}
      >
        {/* Close button */}
        <Button
          type="text"
          icon={<CloseOutlined />}
          onClick={collapseVideo}
          size="small"
          style={{ flexShrink: 0 }}
        />

        {/* Title */}
        <div
          style={{
            flex: 1,
            minWidth: 0,
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
            fontSize: isMobile ? 12 : 14,
            fontWeight: 500,
            color: token.colorText,
          }}
        >
          {title}
        </div>

        {/* Tags + stats */}
        <Space size={8} style={{ flexShrink: 0 }}>
          {video.quality && (
            <Tag color="purple" style={{ margin: 0, fontSize: 10 }}>{video.quality}</Tag>
          )}
          {video.durationSeconds && (
            <Tag style={{ margin: 0, fontSize: 10 }}>{formatDuration(video.durationSeconds)}</Tag>
          )}
        </Space>

        <Space size={12} style={{ color: token.colorTextSecondary, fontSize: 12, flexShrink: 0 }}>
          <span><EyeOutlined /> {formatCount(video.viewCount)}</span>
        </Space>

        {/* Reaction emoji buttons */}
        <ReactionButtons videoId={video.id} currentTime={currentTime} />

        {/* Upvote */}
        <Button
          type={hasUpvoted ? 'primary' : 'text'}
          icon={hasUpvoted ? <LikeFilled /> : <LikeOutlined />}
          onClick={handleUpvote}
          loading={upvoting}
          disabled={hasUpvoted}
          size="small"
          style={{ flexShrink: 0 }}
        >
          {formatCount(upvoteCount)}
        </Button>

        {/* Add to Playlist */}
        {isAuthenticated && (
          <Button
            type="text"
            icon={<OrderedListOutlined />}
            onClick={() => setAddToPlaylistOpen(true)}
            size="small"
            style={{ flexShrink: 0 }}
            title="Add to playlist"
          />
        )}

        {/* Mobile chat toggle */}
        {isMobile && (
          <Button
            type={isMobileChatOpen ? 'primary' : 'text'}
            icon={<CommentOutlined />}
            onClick={() => setIsMobileChatOpen(!isMobileChatOpen)}
            size="small"
          >
            {video.commentCount}
          </Button>
        )}
      </div>

      {/* Mobile chat (collapsible, below info bar) */}
      {isMobileChatOpen && isMobile && (
        <div
          style={{
            background: token.colorBgElevated,
            borderTop: `1px solid ${token.colorBorder}`,
            height: 250,
          }}
        >
          <MediaAuthProvider>
            <LiveChat
              videoId={video.id}
              isOpen={true}
              onRequestLogin={() => {}}
            />
          </MediaAuthProvider>
        </div>
      )}

      {/* Add to Playlist Modal */}
      <AddToPlaylistModal
        videoId={video.id}
        open={addToPlaylistOpen}
        onClose={() => setAddToPlaylistOpen(false)}
      />
    </div>
  );
}
