import { useState } from 'react';
import { bowongAI } from '../../../../sdk/bowongAISDK';
import { useI18n } from '../../../../hooks/useI18n';
import './index.css';

interface UploadCardProps {
  imageUrl: string;
  title: string;
  onUploadSuccess: (imageUrl: string) => void;
  className?: string;
}

export default function UploadCard({ imageUrl, title, onUploadSuccess, className = '' }: UploadCardProps) {
  const [uploading, setUploading] = useState<boolean>(false);
  const { t } = useI18n();

  const handleUpload = async () => {
    if (uploading) {
      alert('正在上传中，请稍候...');
      return;
    }

    try {
      setUploading(true);

      // 使用bowongAI SDK的选择并上传图片功能
      const uploadedImageUrl = await bowongAI.chooseAndUploadImage({
        count: 1,
        onImageSelected: () => {
          console.log('图片选择完成，开始上传...');
        },
        onProgress: progress => {
          console.log(`上传进度: ${progress}%`);
        },
      });

      // 调用父组件的回调函数
      onUploadSuccess(uploadedImageUrl);
    } catch (error: any) {
      console.error('图片上传错误:', error);

      // 处理用户取消选择的情况
      if (error.message === '未选择图片') {
        return; // 用户取消选择，不显示错误
      }

      alert(t('friendsPhoto.uploadFailed') + ': ' + error.message);
    } finally {
      setUploading(false);
    }
  };

  return (
    <div className={`upload-card ${className}`} onClick={handleUpload}>
      <div className="upload-content">
        {uploading ? (
          <div className="upload-placeholder">
            <div className="loading-spinner" />
            <div className="upload-title">上传中...</div>
          </div>
        ) : imageUrl ? (
          <img src={imageUrl} className="upload-image" alt="upload" />
        ) : (
          <div className="upload-placeholder">
            <img src="/assets/icons/photo.png" className="upload-icon" alt="upload icon" />
            <div className="upload-title">{title}</div>
          </div>
        )}
      </div>
    </div>
  );
}
