import { useEffect, useCallback, useRef, useState } from 'react';
import type { MessageAttachment } from '@/types/chat';

interface ImageLightboxProps {
  attachments: MessageAttachment[];
  currentIndex: number;
  onClose: () => void;
}

export function ImageLightbox({ attachments, currentIndex, onClose }: ImageLightboxProps) {
  const [index, setIndex] = useState(currentIndex);
  const [imgLoaded, setImgLoaded] = useState(false);
  const [imgError, setImgError] = useState(false);
  const overlayRef = useRef<HTMLDivElement>(null);

  const current = attachments[index];
  const hasMultiple = attachments.length > 1;

  // 键盘导航
  const handleKeyDown = useCallback(
    (e: KeyboardEvent) => {
      switch (e.key) {
        case 'Escape':
          onClose();
          break;
        case 'ArrowLeft':
          if (hasMultiple) {
            setIndex((prev) => (prev - 1 + attachments.length) % attachments.length);
            setImgLoaded(false);
            setImgError(false);
          }
          break;
        case 'ArrowRight':
          if (hasMultiple) {
            setIndex((prev) => (prev + 1) % attachments.length);
            setImgLoaded(false);
            setImgError(false);
          }
          break;
      }
    },
    [onClose, hasMultiple, attachments.length]
  );

  useEffect(() => {
    document.addEventListener('keydown', handleKeyDown);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', handleKeyDown);
      document.body.style.overflow = '';
    };
  }, [handleKeyDown]);

  // 点击背景关闭
  const handleOverlayClick = useCallback(
    (e: React.MouseEvent) => {
      if (e.target === overlayRef.current) {
        onClose();
      }
    },
    [onClose]
  );

  // 下载当前图片
  const handleDownload = useCallback(async () => {
    if (!current?.url) return;
    try {
      const token = localStorage.getItem('token');
      const resp = await fetch(current.url, {
        headers: token ? { Authorization: `Bearer ${token}` } : {},
      });
      if (!resp.ok) throw new Error('Download failed');
      const blob = await resp.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = current.filename || 'image';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    } catch (err) {
      console.error('[ImageLightbox] 下载失败:', err);
      // 降级：在新窗口打开
      window.open(current.url, '_blank');
    }
  }, [current]);

  if (!current) return null;

  return (
    <div
      ref={overlayRef}
      onClick={handleOverlayClick}
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/85 backdrop-blur-sm animate-fade-in"
      role="dialog"
      aria-modal="true"
      aria-label="图片预览"
    >
      {/* 关闭按钮 */}
      <button
        onClick={onClose}
        className="absolute top-4 right-4 z-10 p-2 rounded-full bg-white/10 hover:bg-white/20 text-white transition-colors"
        aria-label="关闭"
      >
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" className="w-6 h-6">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
        </svg>
      </button>

      {/* 左箭头 */}
      {hasMultiple && (
        <button
          onClick={() => {
            setIndex((prev) => (prev - 1 + attachments.length) % attachments.length);
            setImgLoaded(false);
            setImgError(false);
          }}
          className="absolute left-4 top-1/2 -translate-y-1/2 z-10 p-3 rounded-full bg-white/10 hover:bg-white/20 text-white transition-colors"
          aria-label="上一张"
        >
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" className="w-6 h-6">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
          </svg>
        </button>
      )}

      {/* 右箭头 */}
      {hasMultiple && (
        <button
          onClick={() => {
            setIndex((prev) => (prev + 1) % attachments.length);
            setImgLoaded(false);
            setImgError(false);
          }}
          className="absolute right-4 top-1/2 -translate-y-1/2 z-10 p-3 rounded-full bg-white/10 hover:bg-white/20 text-white transition-colors"
          aria-label="下一张"
        >
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" className="w-6 h-6">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
          </svg>
        </button>
      )}

      {/* 图片容器 */}
      <div className="flex flex-col items-center max-w-[90vw] max-h-[90vh] gap-4">
        {/* 加载中状态 */}
        {!imgLoaded && !imgError && (
          <div className="flex items-center justify-center w-64 h-64 text-white/60">
            <svg className="animate-spin h-10 w-10" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
            </svg>
          </div>
        )}

        {/* 加载失败 */}
        {imgError && (
          <div className="flex flex-col items-center gap-2 text-white/60">
            <span className="text-4xl">🖼️</span>
            <span className="text-sm">图片加载失败</span>
          </div>
        )}

        {/* 图片 */}
        <img
          src={current.url}
          alt={current.filename || '图片'}
          className={`max-w-[85vw] max-h-[70vh] object-contain rounded-lg shadow-2xl ${imgLoaded ? 'block' : 'hidden'}`}
          onLoad={() => setImgLoaded(true)}
          onError={() => setImgError(true)}
        />

        {/* 底部信息栏 */}
        <div className="flex flex-col items-center gap-1 text-white/80 text-sm">
          {/* 计数器 */}
          {hasMultiple && (
            <span className="text-white/50 text-xs">
              {index + 1} / {attachments.length}
            </span>
          )}

          {/* 文件名 */}
          {current.filename && (
            <span className="text-white/70 text-xs">{current.filename}</span>
          )}

          {/* 尺寸信息 */}
          {current.width && current.height && (
            <span className="text-white/50 text-xs">
              {current.width} × {current.height}
            </span>
          )}

          {/* AI 描述 */}
          {current.description && (
            <p className="text-white/80 text-xs text-center max-w-lg mt-1 px-4">
              {current.description}
            </p>
          )}

          {/* 下载按钮 */}
          <button
            onClick={handleDownload}
            className="mt-2 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-white/10 hover:bg-white/20 text-white text-xs transition-colors"
          >
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="w-4 h-4">
              <path fillRule="evenodd" d="M12 2.25a.75.75 0 01.75.75v11.69l3.22-3.22a.75.75 0 111.06 1.06l-4.5 4.5a.75.75 0 01-1.06 0l-4.5-4.5a.75.75 0 111.06-1.06l3.22 3.22V3a.75.75 0 01.75-.75zm-9 13.5a.75.75 0 01.75.75v2.25a1.5 1.5 0 001.5 1.5h13.5a1.5 1.5 0 001.5-1.5V16.5a.75.75 0 011.5 0v2.25a3 3 0 01-3 3H5.25a3 3 0 01-3-3V16.5a.75.75 0 01.75-.75z" clipRule="evenodd" />
            </svg>
            下载
          </button>
        </div>
      </div>
    </div>
  );
}
