import React, { useState, useEffect } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { Loader2, Image as ImageIcon } from 'lucide-react';
import { useLazyLoad } from '../hooks/useLazyLoad';

interface SegmentThumbnailProps {
  segmentId: string;
  size?: 'small' | 'medium' | 'large';
  className?: string;
  thumbnailCache?: Map<string, string>;
  setThumbnailCache?: React.Dispatch<React.SetStateAction<Map<string, string>>>;
}

/**
 * 片段缩略图组件
 * 专门用于显示模板匹配结果中的片段缩略图
 * 遵循Tauri开发规范的组件设计模式
 * 支持懒加载、缓存机制、错误处理
 */
export const SegmentThumbnail: React.FC<SegmentThumbnailProps> = ({
  segmentId,
  size = 'medium',
  className = '',
  thumbnailCache = new Map(),
  setThumbnailCache = () => {},
}) => {
  const [loading, setLoading] = useState(false);
  const [thumbnailUrl, setThumbnailUrl] = useState<string | null>(null);
  const [error, setError] = useState(false);

  // 使用懒加载Hook，当缩略图容器可见时才开始加载
  const { isVisible, elementRef } = useLazyLoad(0.1, '100px');

  // 根据size确定尺寸
  const getSizeClasses = () => {
    switch (size) {
      case 'small':
        return 'w-12 h-12';
      case 'medium':
        return 'w-16 h-16';
      case 'large':
        return 'w-24 h-24';
      default:
        return 'w-16 h-16';
    }
  };

  // 获取图标尺寸
  const getIconSize = () => {
    switch (size) {
      case 'small':
        return 'w-3 h-3';
      case 'medium':
        return 'w-4 h-4';
      case 'large':
        return 'w-6 h-6';
      default:
        return 'w-4 h-4';
    }
  };

  useEffect(() => {
    // 只有当元素可见时才加载缩略图
    if (!isVisible || !segmentId) return;

    const loadThumbnail = async () => {
      // 检查缓存
      if (thumbnailCache.has(segmentId)) {
        const cachedUrl = thumbnailCache.get(segmentId);
        setThumbnailUrl(cachedUrl || null);
        return;
      }

      // 加载缩略图
      setLoading(true);
      setError(false);
      
      try {
        console.log('获取片段缩略图:', segmentId);
        const dataUrl = await invoke<string>('get_segment_thumbnail_base64', {
          segmentId: segmentId
        });
        console.log('获取缩略图成功');
        setThumbnailUrl(dataUrl);

        // 更新缓存
        const newCache = new Map(thumbnailCache);
        newCache.set(segmentId, dataUrl);
        setThumbnailCache(newCache);
      } catch (error) {
        console.error('获取缩略图失败:', error);
        setError(true);
      } finally {
        setLoading(false);
      }
    };

    loadThumbnail();
  }, [isVisible, segmentId, thumbnailCache, setThumbnailCache]);

  return (
    <div
      ref={elementRef}
      className={`${getSizeClasses()} bg-gray-100 rounded-lg flex items-center justify-center flex-shrink-0 overflow-hidden ${className}`}
    >
      {loading ? (
        <Loader2 className={`${getIconSize()} animate-spin text-blue-600`} />
      ) : thumbnailUrl && !error ? (
        <img
          src={thumbnailUrl}
          alt="片段缩略图"
          className="w-full h-full object-cover rounded-lg"
          onError={() => {
            setError(true);
            setThumbnailUrl(null);
          }}
        />
      ) : (
        <ImageIcon className={`${getIconSize()} text-gray-400`} />
      )}
    </div>
  );
};
