import { useState, useEffect, useRef } from 'react';
import { Typography, Spin, theme, Grid } from 'antd';
import { LeftOutlined, RightOutlined } from '@ant-design/icons';
import PlaylistCard from './PlaylistCard';
import { mediaPublicApi } from '@/lib/media-public-api';
import type { PlaylistSummary } from '@/types/media';

const { useBreakpoint } = Grid;

export default function FeaturedPlaylistCarousel() {
  const { token } = theme.useToken();
  const screens = useBreakpoint();
  const isMobile = !screens.md;
  const scrollRef = useRef<HTMLDivElement>(null);

  const [playlists, setPlaylists] = useState<PlaylistSummary[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchFeatured = async () => {
      try {
        const { data } = await mediaPublicApi.get('/playlists/featured', {
          params: { limit: 12 },
        });
        setPlaylists(data.data || []);
      } catch {
        // Silent fail — not critical
      } finally {
        setLoading(false);
      }
    };
    fetchFeatured();
  }, []);

  const scroll = (direction: 'left' | 'right') => {
    if (!scrollRef.current) return;
    const scrollAmount = isMobile ? 260 : 300;
    scrollRef.current.scrollBy({
      left: direction === 'left' ? -scrollAmount : scrollAmount,
      behavior: 'smooth',
    });
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: 24 }}>
        <Spin />
      </div>
    );
  }

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

  return (
    <div style={{ marginBottom: 24 }}>
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          marginBottom: 12,
        }}
      >
        <Typography.Title level={5} style={{ margin: 0 }}>
          Featured Playlists
        </Typography.Title>

        {playlists.length > 3 && (
          <div style={{ display: 'flex', gap: 8 }}>
            <div
              onClick={() => scroll('left')}
              style={{
                width: 32,
                height: 32,
                borderRadius: '50%',
                border: `1px solid ${token.colorBorderSecondary}`,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                cursor: 'pointer',
                color: token.colorTextSecondary,
                transition: 'all 0.2s',
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.borderColor = token.colorPrimary;
                e.currentTarget.style.color = token.colorPrimary;
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.borderColor = token.colorBorderSecondary;
                e.currentTarget.style.color = token.colorTextSecondary;
              }}
            >
              <LeftOutlined style={{ fontSize: 12 }} />
            </div>
            <div
              onClick={() => scroll('right')}
              style={{
                width: 32,
                height: 32,
                borderRadius: '50%',
                border: `1px solid ${token.colorBorderSecondary}`,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                cursor: 'pointer',
                color: token.colorTextSecondary,
                transition: 'all 0.2s',
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.borderColor = token.colorPrimary;
                e.currentTarget.style.color = token.colorPrimary;
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.borderColor = token.colorBorderSecondary;
                e.currentTarget.style.color = token.colorTextSecondary;
              }}
            >
              <RightOutlined style={{ fontSize: 12 }} />
            </div>
          </div>
        )}
      </div>

      <div
        ref={scrollRef}
        style={{
          display: 'flex',
          gap: 16,
          overflowX: 'auto',
          scrollSnapType: 'x mandatory',
          scrollbarWidth: 'none',
          msOverflowStyle: 'none',
          paddingBottom: 4,
        }}
      >
        {playlists.map((playlist) => (
          <div
            key={playlist.id}
            style={{
              minWidth: isMobile ? 240 : 280,
              maxWidth: isMobile ? 240 : 280,
              scrollSnapAlign: 'start',
              flexShrink: 0,
            }}
          >
            <PlaylistCard playlist={playlist} />
          </div>
        ))}
      </div>
    </div>
  );
}
