import { useRef, useState, useEffect } from 'react';
import { Button, Space, Tag, Grid, theme, Spin, message } from 'antd';
import {
  CloseOutlined,
  LikeOutlined,
  LikeFilled,
  EyeOutlined,
  LeftOutlined,
  RightOutlined,
  PictureOutlined,
  AppstoreOutlined,
} from '@ant-design/icons';
import { useExpandedVideo } from '@/contexts/ExpandedVideoContext';
import { mediaPublicApi } from '@/lib/media-public-api';
import type { PublicAlbum } from '@/types/media';
import axios from 'axios';

const { useBreakpoint } = Grid;

interface AlbumPhoto {
  id: number;
  title: string | null;
  width: number | null;
  height: number | null;
  format: string | null;
  thumbnailUrl: string;
  imageUrl: string;
}

interface ExpandedAlbumCardProps {
  album: PublicAlbum;
}

export default function ExpandedAlbumCard({ album }: ExpandedAlbumCardProps) {
  const { token } = theme.useToken();
  const screens = useBreakpoint();
  const isMobile = !screens.md;
  const { collapseVideo } = useExpandedVideo();

  const containerRef = useRef<HTMLDivElement>(null);
  const [hasUpvoted, setHasUpvoted] = useState(false);
  const [upvoteCount, setUpvoteCount] = useState(album.upvoteCount);
  const [upvoting, setUpvoting] = useState(false);
  const [isExpanding, setIsExpanding] = useState(true);
  const [photos, setPhotos] = useState<AlbumPhoto[]>([]);
  const [loading, setLoading] = useState(true);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [imageLoading, setImageLoading] = useState(true);

  const pad = isMobile ? 8 : 12;

  // Fetch album photos
  useEffect(() => {
    const fetchPhotos = async () => {
      try {
        const { data } = await mediaPublicApi.get(`/public/albums/${album.id}`);
        setPhotos(data.photos || []);
      } catch {
        // Silent fail
      } finally {
        setLoading(false);
      }
    };
    fetchPhotos();
  }, [album.id]);

  // Keyboard navigation
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'Escape') collapseVideo();
      if (e.key === 'ArrowLeft') setCurrentIndex(prev => Math.max(0, prev - 1));
      if (e.key === 'ArrowRight') setCurrentIndex(prev => Math.min(photos.length - 1, prev + 1));
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [collapseVideo, photos.length]);

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

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

  const handleUpvote = async () => {
    if (upvoting || hasUpvoted) return;
    try {
      setUpvoting(true);
      // Albums don't have a direct upvote — upvote the current photo instead
      if (photos[currentIndex]) {
        await mediaPublicApi.post(`/photos/${photos[currentIndex].id}/upvote`);
      }
      setHasUpvoted(true);
      setUpvoteCount(prev => prev + 1);
    } catch (error: unknown) {
      if (axios.isAxiosError(error) && error.response?.status === 401) {
        message.info('Please log in to upvote');
      }
    } finally {
      setUpvoting(false);
    }
  };

  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();
  };

  const currentPhoto = photos[currentIndex];

  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,
        marginLeft: -pad,
        marginRight: -pad,
        width: `calc(100% + ${pad * 2}px)`,
      }}
    >
      {/* Image carousel */}
      <div
        style={{
          position: 'relative',
          width: '100%',
          maxHeight: isMobile ? 'calc(100vh - 160px)' : 'calc(100vh - 120px)',
          background: '#000',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          minHeight: 300,
        }}
      >
        {loading ? (
          <Spin size="large" />
        ) : currentPhoto ? (
          <>
            {imageLoading && (
              <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Spin size="large" />
              </div>
            )}
            <img
              key={currentPhoto.id}
              src={currentPhoto.imageUrl}
              alt={currentPhoto.title || `Photo ${currentIndex + 1}`}
              onLoad={() => setImageLoading(false)}
              style={{
                maxWidth: '100%',
                maxHeight: isMobile ? 'calc(100vh - 160px)' : 'calc(100vh - 120px)',
                objectFit: 'contain',
              }}
            />

            {/* Left arrow */}
            {currentIndex > 0 && (
              <Button
                type="text"
                icon={<LeftOutlined />}
                onClick={(e) => {
                  e.stopPropagation();
                  setImageLoading(true);
                  setCurrentIndex(prev => prev - 1);
                }}
                style={{
                  position: 'absolute',
                  left: 8,
                  top: '50%',
                  transform: 'translateY(-50%)',
                  background: 'rgba(0,0,0,0.6)',
                  color: '#fff',
                  borderRadius: '50%',
                  width: 40,
                  height: 40,
                }}
              />
            )}

            {/* Right arrow */}
            {currentIndex < photos.length - 1 && (
              <Button
                type="text"
                icon={<RightOutlined />}
                onClick={(e) => {
                  e.stopPropagation();
                  setImageLoading(true);
                  setCurrentIndex(prev => prev + 1);
                }}
                style={{
                  position: 'absolute',
                  right: 8,
                  top: '50%',
                  transform: 'translateY(-50%)',
                  background: 'rgba(0,0,0,0.6)',
                  color: '#fff',
                  borderRadius: '50%',
                  width: 40,
                  height: 40,
                }}
              />
            )}

            {/* Photo counter */}
            <div
              style={{
                position: 'absolute',
                top: 12,
                right: 12,
                background: 'rgba(0,0,0,0.7)',
                color: '#fff',
                padding: '4px 12px',
                borderRadius: 16,
                fontSize: 13,
                fontWeight: 500,
              }}
            >
              {currentIndex + 1} / {photos.length}
            </div>
          </>
        ) : (
          <div style={{ color: '#666', fontSize: 16 }}>No photos in this album</div>
        )}
      </div>

      {/* Thumbnail strip */}
      {photos.length > 1 && (
        <div
          style={{
            display: 'flex',
            gap: 4,
            padding: '8px 12px',
            overflowX: 'auto',
            background: token.colorBgElevated,
            borderTop: `1px solid ${token.colorBorder}`,
          }}
        >
          {photos.map((p, idx) => (
            <div
              key={p.id}
              onClick={() => {
                setImageLoading(true);
                setCurrentIndex(idx);
              }}
              style={{
                width: 48,
                height: 36,
                flexShrink: 0,
                borderRadius: 4,
                overflow: 'hidden',
                cursor: 'pointer',
                border: idx === currentIndex
                  ? `2px solid ${token.colorPrimary}`
                  : '2px solid transparent',
                opacity: idx === currentIndex ? 1 : 0.6,
                transition: 'all 0.2s ease',
              }}
            >
              <img
                src={p.thumbnailUrl}
                alt=""
                style={{ width: '100%', height: '100%', objectFit: 'cover' }}
              />
            </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',
        }}
      >
        <Button
          type="text"
          icon={<CloseOutlined />}
          onClick={collapseVideo}
          size="small"
          style={{ flexShrink: 0 }}
        />

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

        <Space size={8} style={{ flexShrink: 0 }}>
          <Tag style={{ margin: 0, fontSize: 10 }}>
            <AppstoreOutlined /> Album
          </Tag>
          <Tag style={{ margin: 0, fontSize: 10 }}>
            <PictureOutlined /> {album.photoCount} photos
          </Tag>
        </Space>

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

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