import { useI18n } from '@/hooks/useI18n';
import { fileApi } from '@/services/file-api';
import { useState } from 'react';
import './index.css';

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

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

  const handleUpload = async () => {
    if (disabled) {
      onLogin();
      return;
    }

    if (uploading) {
      alert('Uploading, please wait...');
      return;
    }

    try {
      // 使用bowongAI SDK的选择并上传图片功能
      const uploadedImageUrl = await fileApi.chooseAndUploadImage({
        count: 1,
        onImageSelected: () => {
          setUploading(true);
        },
        onProgress: progress => {
          console.log(`Upload progress: ${progress}%`);
        },
      });

      // 调用父组件的回调函数
      onUploadSuccess(uploadedImageUrl);
    } catch (error: any) {
      setUploading(false);
      console.error('Upload error:', error);

      // 处理用户取消选择的情况
      if (error.message === 'No image selected') {
        setUploading(false);
        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">Uploading...</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>
  );
}
