import { useEffect, useRef } from 'react';
import { Typography, Space, theme } from 'antd';
import { PlayCircleOutlined, ClockCircleOutlined } from '@ant-design/icons';
import type { PlaylistVideoItem } from '@/types/media';

const { Text } = Typography;

interface PlaylistSidebarPanelProps {
  playlistName: string;
  description?: string | null;
  videos: PlaylistVideoItem[];
  currentVideoId: number | null;
  onVideoSelect: (mediaId: number) => void;
}

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

export default function PlaylistSidebarPanel({
  playlistName,
  description,
  videos,
  currentVideoId,
  onVideoSelect,
}: PlaylistSidebarPanelProps) {
  const { token } = theme.useToken();
  const currentRef = useRef<HTMLDivElement>(null);

  // Auto-scroll to the current playing video
  useEffect(() => {
    if (currentRef.current) {
      currentRef.current.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }
  }, [currentVideoId]);

  const currentIndex = videos.findIndex((v) => v.mediaId === currentVideoId);

  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
        height: '100%',
        background: token.colorBgContainer,
        borderLeft: `1px solid rgba(255,255,255,0.06)`,
      }}
    >
      {/* Header */}
      <div
        style={{
          padding: '16px',
          borderBottom: '1px solid rgba(255,255,255,0.06)',
          flexShrink: 0,
        }}
      >
        <Text strong style={{ fontSize: 15, display: 'block', marginBottom: 4 }}>
          {playlistName}
        </Text>
        {description && (
          <Text
            type="secondary"
            style={{
              fontSize: 12,
              display: '-webkit-box',
              WebkitLineClamp: 2,
              WebkitBoxOrient: 'vertical' as const,
              overflow: 'hidden',
              marginBottom: 4,
            }}
          >
            {description}
          </Text>
        )}
        <Text type="secondary" style={{ fontSize: 12 }}>
          {currentIndex + 1} / {videos.length} videos
        </Text>
      </div>

      {/* Video list */}
      <div
        style={{
          flex: 1,
          overflowY: 'auto',
          overflowX: 'hidden',
        }}
      >
        {videos.map((item, index) => {
          const isCurrent = item.mediaId === currentVideoId;
          const isNext = index === currentIndex + 1;
          const title =
            item.video.title || item.video.filename.replace(/\.[^/.]+$/, '');

          return (
            <div
              key={item.id}
              ref={isCurrent ? currentRef : undefined}
              onClick={() => onVideoSelect(item.mediaId)}
              style={{
                display: 'flex',
                gap: 10,
                padding: '10px 16px',
                cursor: 'pointer',
                background: isCurrent
                  ? `${token.colorPrimary}22`
                  : 'transparent',
                borderLeft: isCurrent
                  ? `3px solid ${token.colorPrimary}`
                  : '3px solid transparent',
                transition: 'all 0.15s ease',
              }}
              onMouseEnter={(e) => {
                if (!isCurrent) {
                  e.currentTarget.style.background = 'rgba(255,255,255,0.04)';
                }
              }}
              onMouseLeave={(e) => {
                if (!isCurrent) {
                  e.currentTarget.style.background = 'transparent';
                }
              }}
            >
              {/* Position number */}
              <div
                style={{
                  width: 24,
                  flexShrink: 0,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}
              >
                {isCurrent ? (
                  <PlayCircleOutlined
                    style={{ color: token.colorPrimary, fontSize: 16 }}
                  />
                ) : (
                  <Text
                    type="secondary"
                    style={{ fontSize: 12, fontWeight: 500 }}
                  >
                    {index + 1}
                  </Text>
                )}
              </div>

              {/* Thumbnail */}
              <div
                style={{
                  width: 64,
                  height: 36,
                  flexShrink: 0,
                  borderRadius: 4,
                  overflow: 'hidden',
                  background: '#000',
                }}
              >
                {item.video.thumbnailUrl ? (
                  <img
                    src={`/media${item.video.thumbnailUrl}`}
                    alt=""
                    style={{
                      width: '100%',
                      height: '100%',
                      objectFit: 'cover',
                    }}
                  />
                ) : (
                  <div
                    style={{
                      width: '100%',
                      height: '100%',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      color: '#444',
                      fontSize: 16,
                    }}
                  >
                    <PlayCircleOutlined />
                  </div>
                )}
              </div>

              {/* Video info */}
              <div style={{ flex: 1, minWidth: 0 }}>
                {isNext && (
                  <Text
                    style={{
                      fontSize: 10,
                      color: token.colorPrimary,
                      textTransform: 'uppercase',
                      fontWeight: 600,
                      letterSpacing: '0.5px',
                      display: 'block',
                      marginBottom: 2,
                    }}
                  >
                    Up Next
                  </Text>
                )}
                <Text
                  ellipsis
                  style={{
                    fontSize: 13,
                    display: 'block',
                    fontWeight: isCurrent ? 500 : 400,
                  }}
                >
                  {title}
                </Text>
                <Space size={8} style={{ fontSize: 11 }}>
                  <Text type="secondary">
                    <ClockCircleOutlined style={{ marginRight: 3 }} />
                    {formatDuration(item.video.durationSeconds)}
                  </Text>
                </Space>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
