import React, { useState, useRef, useEffect } from 'react';
import { Upload, X, ZoomIn, Loader2 } from 'lucide-react';
import { ImageWithFallback } from '../figma/ImageWithFallback';
import { fileApi } from '../../api/file';
import { toast } from 'sonner';

interface UploadImgProps {
  value?: string;
  onChange?: (value: string) => void;
  limit?: number;
  height?: string;
  width?: string;
}

export default function UploadImg({
  value,
  onChange,
  limit = 1,
  height = '64px',
  width = '64px',
}: UploadImgProps) {
  const [previewUrl, setPreviewUrl] = useState<string | undefined>(value);
  const [showPreview, setShowPreview] = useState(false);
  const [uploading, setUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // 同步外部 value 变化
  useEffect(() => {
    if (value) {
      // 如果 value 是 URL，直接使用
      // 如果 value 是 data URI，直接使用
      // 如果 value 是纯 base64 字符串，转换为 data URI 用于预览
      if (value.startsWith('http://') || value.startsWith('https://')) {
        setPreviewUrl(value);
      } else if (value.startsWith('data:')) {
        setPreviewUrl(value);
      } else {
        setPreviewUrl(`data:image/jpeg;base64,${value}`);
      }
    } else {
      setPreviewUrl(undefined);
    }
  }, [value]);

  // 处理文件选择
  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      toast.error('请选择图片文件');
      return;
    }

    // 检查文件大小 (限制为5MB)
    if (file.size > 5 * 1024 * 1024) {
      toast.error('图片大小不能超过5MB');
      return;
    }

    // 先创建预览（使用本地 URL）
    const localPreviewUrl = URL.createObjectURL(file);
    setPreviewUrl(localPreviewUrl);
    setUploading(true);

    try {
      // 上传文件获取 URL
      const fileUrl = await fileApi.upload(file);
      // 释放本地预览 URL
      URL.revokeObjectURL(localPreviewUrl);
      // 设置服务器返回的 URL 作为预览
      setPreviewUrl(fileUrl);
      // 传递 URL 给父组件
      onChange?.(fileUrl);
    } catch (error: any) {
      // 上传失败，清除预览
      URL.revokeObjectURL(localPreviewUrl);
      setPreviewUrl(undefined);
      toast.error(error.message || '图片上传失败');
      // 清空文件输入
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    } finally {
      setUploading(false);
    }
  };

  // 删除图片
  const handleRemove = (e: React.MouseEvent) => {
    e.stopPropagation();
    setPreviewUrl(undefined);
    onChange?.('');
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  // 打开文件选择器
  const handleClick = () => {
    fileInputRef.current?.click();
  };

  return (
    <div>
      <div
        className="relative border-2 border-dashed border-gray-300 rounded-lg cursor-pointer hover:border-blue-400 transition-colors flex items-center justify-center bg-gray-50"
        style={{ height, width }}
        onClick={handleClick}
      >
        {uploading ? (
          <div className="flex flex-col items-center justify-center gap-2 text-gray-400">
            <Loader2 className="w-6 h-6 animate-spin" />
            <span className="text-xs">上传中...</span>
          </div>
        ) : previewUrl ? (
          <div className="relative w-full h-full group">
            <ImageWithFallback
              src={previewUrl}
              alt="预览"
              className="w-full h-full object-cover rounded-lg"
            />
            <div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2 rounded-lg">
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  setShowPreview(true);
                }}
                className="p-1 bg-white/80 rounded hover:bg-white transition-colors"
                title="查看大图"
              >
                <ZoomIn className="w-4 h-4 text-gray-700" />
              </button>
              <button
                onClick={handleRemove}
                className="p-1 bg-white/80 rounded hover:bg-white transition-colors"
                title="删除"
              >
                <X className="w-4 h-4 text-gray-700" />
              </button>
            </div>
          </div>
        ) : (
          <div className="flex flex-col items-center justify-center gap-2 text-gray-400">
            <Upload className="w-6 h-6" />
            <span className="text-xs">上传图片</span>
          </div>
        )}
        <input
          ref={fileInputRef}
          type="file"
          accept="image/*"
          style={{ display: 'none' }}
          onChange={handleFileChange}
        />
      </div>

      {/* 图片预览弹窗 */}
      {showPreview && previewUrl && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/80"
          onClick={() => setShowPreview(false)}
        >
          <div className="relative max-w-4xl max-h-[90vh] p-4">
            <button
              onClick={() => setShowPreview(false)}
              className="absolute top-2 right-2 p-2 bg-white/80 rounded-full hover:bg-white transition-colors"
            >
              <X className="w-5 h-5 text-gray-700" />
            </button>
            <ImageWithFallback
              src={previewUrl}
              alt="预览"
              className="max-w-full max-h-[90vh] object-contain rounded-lg"
            />
          </div>
        </div>
      )}
    </div>
  );
}

