import { useState, useEffect, useRef, useCallback } from 'react';
import {
  useParams,
  useNavigate,
  useSearchParams,
} from 'react-router-dom';
import {
  Typography,
  Button,
  Space,
  Spin,
  Divider,
  Grid,
  message,
  theme,
} from 'antd';
import {
  ArrowLeftOutlined,
  ShareAltOutlined,
  EyeOutlined,
} from '@ant-design/icons';
import VideoPlayer, { VideoPlayerRef } from '@/components/media/VideoPlayer';
import PlaylistSidebarPanel from '@/components/media/PlaylistSidebarPanel';
import ReactionButtons from '@/components/media/ReactionButtons';
import CommentSection from '@/components/media/CommentSection';
import PublicNavBar from '@/components/PublicNavBar';
import { mediaPublicApi } from '@/lib/media-public-api';
import { mediaApi } from '@/lib/media-api';
import type { PlaylistDetail } from '@/types/media';
import axios from 'axios';

const { Title, Text } = Typography;
const { useBreakpoint } = Grid;

export default function PlaylistViewerPage() {
  const { playlistId, token: shareToken } = useParams<{
    playlistId?: string;
    token?: string;
  }>();
  const [searchParams, setSearchParams] = useSearchParams();
  const navigate = useNavigate();
  const screens = useBreakpoint();
  const isMobile = !screens.md;
  const { token: themeToken } = theme.useToken();

  const playerRef = useRef<VideoPlayerRef>(null);

  const [playlist, setPlaylist] = useState<PlaylistDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [currentVideoId, setCurrentVideoId] = useState<number | null>(null);

  // Determine current video from URL or default to first
  const videoParam = searchParams.get('v');

  // Fetch playlist
  useEffect(() => {
    const fetchPlaylist = async () => {
      try {
        setLoading(true);
        let data: PlaylistDetail;

        if (shareToken) {
          const res = await mediaPublicApi.get(`/playlists/share/${shareToken}`);
          data = res.data;
        } else if (playlistId) {
          const res = await mediaPublicApi.get(`/playlists/${playlistId}`);
          data = res.data;
        } else {
          navigate('/gallery/curated');
          return;
        }

        setPlaylist(data);

        // Set initial video
        const requestedVideoId = videoParam ? parseInt(videoParam) : null;
        if (
          requestedVideoId &&
          data.videos?.some((v: any) => v.mediaId === requestedVideoId)
        ) {
          setCurrentVideoId(requestedVideoId);
        } else if (data.videos?.length > 0) {
          setCurrentVideoId(data.videos[0]!.mediaId);
        }
      } catch (error: unknown) {
        if (axios.isAxiosError(error) && error.response?.status === 404) {
          message.error('Playlist not found');
          navigate('/gallery/curated');
        } else {
          message.error('Failed to load playlist');
        }
      } finally {
        setLoading(false);
      }
    };

    fetchPlaylist();
  }, [playlistId, shareToken]);

  // Record playlist view on mount
  useEffect(() => {
    if (!playlist) return;

    const recordView = async () => {
      try {
        await mediaPublicApi.post(`/playlists/${playlist.id}/view`);
      } catch {
        // Silent fail
      }
    };

    recordView();
  }, [playlist?.id]);

  // Listen for video ended event to auto-advance
  useEffect(() => {
    if (!playerRef.current || !playlist || !currentVideoId) return;

    const videoElement = playerRef.current.getVideoElement();
    if (!videoElement) return;

    const handleEnded = () => {
      const currentIndex = playlist.videos.findIndex(
        (v) => v.mediaId === currentVideoId
      );
      if (currentIndex >= 0 && currentIndex < playlist.videos.length - 1) {
        const nextVideo = playlist.videos[currentIndex + 1]!;
        handleVideoSelect(nextVideo.mediaId);
      }
    };

    videoElement.addEventListener('ended', handleEnded);
    return () => videoElement.removeEventListener('ended', handleEnded);
  }, [currentVideoId, playlist?.videos]);

  const handleVideoSelect = useCallback(
    (mediaId: number) => {
      setCurrentVideoId(mediaId);
      setSearchParams({ v: mediaId.toString() }, { replace: true });
      window.scrollTo({ top: 0, behavior: 'smooth' });
    },
    [setSearchParams]
  );

  const handleShare = async () => {
    if (!playlist) return;

    try {
      let token = playlist.shareToken;
      if (!token && playlist.isOwner) {
        const { data } = await mediaApi.post(`/playlists/${playlist.id}/share`);
        token = data.shareToken;
        setPlaylist((prev) => (prev ? { ...prev, shareToken: token } : prev));
      }

      const url = token
        ? `${window.location.origin}/gallery/curated/share/${token}`
        : `${window.location.origin}/gallery/curated/${playlist.id}`;

      await navigator.clipboard.writeText(url);
      message.success('Link copied to clipboard');
    } catch {
      message.error('Failed to copy link');
    }
  };

  // Get current video info
  const currentVideo = playlist?.videos.find(
    (v) => v.mediaId === currentVideoId
  );
  const currentTitle = currentVideo
    ? currentVideo.video.title ||
      currentVideo.video.filename.replace(/\.[^/.]+$/, '')
    : '';

  if (loading) {
    return (
      <>
        <PublicNavBar activePath="/gallery" />
        <div style={{ textAlign: 'center', padding: 100 }}>
          <Spin size="large" />
        </div>
      </>
    );
  }

  if (!playlist) return null;

  return (
    <div
      style={{
        minHeight: '100vh',
        background: themeToken.colorBgLayout,
        color: themeToken.colorText,
      }}
    >
      <PublicNavBar activePath="/gallery" />
      {/* Top bar */}
      <div
        style={{
          padding: isMobile ? '8px 12px' : '12px 24px',
          borderBottom: '1px solid rgba(255,255,255,0.06)',
          display: 'flex',
          alignItems: 'center',
          gap: 12,
        }}
      >
        <Button
          icon={<ArrowLeftOutlined />}
          type="text"
          onClick={() => navigate('/gallery/curated')}
        />
        <div style={{ flex: 1, minWidth: 0 }}>
          <Text strong ellipsis style={{ display: 'block', fontSize: 15 }}>
            {playlist.name}
          </Text>
          {playlist.description && (
            <Text
              type="secondary"
              ellipsis
              style={{ display: 'block', fontSize: 12, lineHeight: '1.3' }}
            >
              {playlist.description}
            </Text>
          )}
        </div>
        <Button icon={<ShareAltOutlined />} type="text" onClick={handleShare} />
      </div>

      {/* Main content */}
      <div
        style={{
          display: isMobile ? 'block' : 'flex',
          height: isMobile ? 'auto' : 'calc(100vh - 49px)',
        }}
      >
        {/* Video area */}
        <div
          style={{
            flex: 1,
            overflow: isMobile ? 'visible' : 'auto',
            padding: isMobile ? 12 : 24,
          }}
        >
          {/* Player */}
          {currentVideoId && (
            <div style={{ marginBottom: 16 }}>
              <VideoPlayer
                key={currentVideoId}
                ref={playerRef}
                videoId={currentVideoId}
                autoplay
                width="100%"
              />
            </div>
          )}

          {/* Video title + meta */}
          <Title level={4} style={{ marginBottom: 8 }}>
            {currentTitle}
          </Title>

          <Space size={16} wrap style={{ marginBottom: 16 }}>
            {currentVideo && (
              <Text type="secondary">
                <EyeOutlined style={{ marginRight: 4 }} />
                {currentVideo.video.viewCount} views
              </Text>
            )}
            <Text type="secondary">
              Playing {(playlist.videos.findIndex((v) => v.mediaId === currentVideoId) ?? 0) + 1} of{' '}
              {playlist.videos.length}
            </Text>
          </Space>

          {/* Mobile: Horizontal video strip */}
          {isMobile && playlist.videos.length > 1 && (
            <div
              style={{
                display: 'flex',
                gap: 8,
                overflowX: 'auto',
                marginBottom: 16,
                paddingBottom: 8,
                scrollbarWidth: 'none',
              }}
            >
              {playlist.videos.map((item) => {
                const title =
                  item.video.title ||
                  item.video.filename.replace(/\.[^/.]+$/, '');
                const isCurrent = item.mediaId === currentVideoId;

                return (
                  <div
                    key={item.id}
                    onClick={() => handleVideoSelect(item.mediaId)}
                    style={{
                      minWidth: 140,
                      maxWidth: 140,
                      cursor: 'pointer',
                      opacity: isCurrent ? 1 : 0.7,
                      borderBottom: isCurrent
                        ? `2px solid ${themeToken.colorPrimary}`
                        : '2px solid transparent',
                      paddingBottom: 4,
                      flexShrink: 0,
                    }}
                  >
                    <div
                      style={{
                        width: '100%',
                        paddingTop: '56.25%',
                        position: 'relative',
                        borderRadius: 4,
                        overflow: 'hidden',
                        background: '#000',
                        marginBottom: 4,
                      }}
                    >
                      {item.video.thumbnailUrl && (
                        <img
                          src={`/media${item.video.thumbnailUrl}`}
                          alt=""
                          style={{
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            width: '100%',
                            height: '100%',
                            objectFit: 'cover',
                          }}
                        />
                      )}
                    </div>
                    <Text
                      ellipsis
                      style={{
                        fontSize: 11,
                        fontWeight: isCurrent ? 600 : 400,
                        display: 'block',
                      }}
                    >
                      {title}
                    </Text>
                  </div>
                );
              })}
            </div>
          )}

          {/* Reactions */}
          {currentVideoId && (
            <div style={{ marginBottom: 16 }}>
              <ReactionButtons videoId={currentVideoId} currentTime={0} />
            </div>
          )}

          <Divider />

          {/* Comments */}
          {currentVideoId && <CommentSection videoId={currentVideoId} />}
        </div>

        {/* Desktop: Playlist sidebar */}
        {!isMobile && (
          <div
            style={{
              width: 360,
              flexShrink: 0,
              height: '100%',
              overflow: 'hidden',
            }}
          >
            <PlaylistSidebarPanel
              playlistName={playlist.name}
              description={playlist.description}
              videos={playlist.videos}
              currentVideoId={currentVideoId}
              onVideoSelect={handleVideoSelect}
            />
          </div>
        )}
      </div>
    </div>
  );
}
