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

interface WatermarkTemplateThumbnailProps {
  templateId: string;
  size?: 'small' | 'medium' | 'large';
  className?: string;
  thumbnailCache?: Map<string, string>;
  setThumbnailCache?: (cache: Map<string, string>) => void;
}

/**
 * 水印模板缩略图组件
 * 参考其他页面的缩略图实现模式
 */
export const WatermarkTemplateThumbnail: React.FC<WatermarkTemplateThumbnailProps> = ({
  templateId,
  size = 'medium',
  className = '',
  thumbnailCache = new Map(),
  setThumbnailCache = () => {},
}) => {
  const [loading, setLoading] = useState(false);
  const [thumbnailUrl, setThumbnailUrl] = useState<string | null>(null);
  const [error, setError] = useState(false);

  // 根据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 (!templateId) return;

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

      // 加载缩略图
      setLoading(true);
      setError(false);
      
      try {
        console.log('获取水印模板缩略图:', templateId);
        const dataUrl = await invoke<string>('get_watermark_template_thumbnail', {
          templateId: templateId
        });
        console.log('获取缩略图成功');
        setThumbnailUrl(dataUrl);

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

    loadThumbnail();
  }, [templateId, thumbnailCache, setThumbnailCache]);

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