import { Platform } from 'react-native';
import { request, PERMISSIONS, RESULTS } from 'react-native-permissions';
import { launchImageLibrary } from 'react-native-image-picker';
import { apiService } from './api';
import Toast from 'react-native-toast-message';

interface UploadResponse {
  success: boolean;
  imageUrl?: string;
  error?: string;
}

interface QiniuUploadInfo {
  token: string;
  domain: string;
}

class UploadImageService {
  private static instance: UploadImageService;
  private uploadInfo: QiniuUploadInfo | null = null;

  private constructor() {}

  public static getInstance(): UploadImageService {
    if (!UploadImageService.instance) {
      UploadImageService.instance = new UploadImageService();
    }
    return UploadImageService.instance;
  }

  private showToast(message: string, type: 'success' | 'error' | 'info' = 'info') {
    Toast.show({
      type,
      text1: message,
      position: 'top',
      topOffset: Platform.OS === 'ios' ? 60 : 20,
      visibilityTime: 2000,
    });
  }

  private async checkPermission(): Promise<boolean> {
    try {
      const permission = Platform.select({
        android: PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE,
        ios: PERMISSIONS.IOS.PHOTO_LIBRARY,
        default: PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE,
      });

      const result = await request(permission);
      
      if (result !== RESULTS.GRANTED) {
        this.showToast('请在设置中授予相册访问权限', 'error');
        return false;
      }
      
      return true;
    } catch (error) {
      console.error('Permission check error:', error);
      return false;
    }
  }

  private async getQiniuToken(): Promise<boolean> {
    try {
      const response = await apiService.getQiniuToken();
      if (response.code == 200) {
        this.uploadInfo = {
          token: response.token,
          domain: response.domain
        };
        return true;
      }
      this.showToast('获取上传凭证失败', 'error');
      return false;
    } catch (error) {
      console.error('Get qiniu token error:', error);
      this.showToast('获取上传凭证失败', 'error');
      return false;
    }
  }

  private generateKey(): string {
    const timestamp = Date.now();
    const random = Math.random().toString(36).substring(2, 15);
    return `bike/img/static/${timestamp}_${random}`;
  }

  private async uploadToQiniu(uri: string, key: string): Promise<UploadResponse> {
    if (!this.uploadInfo?.token) {
      return { success: false, error: '上传凭证无效' };
    }

    const formData = new FormData();
    formData.append('token', this.uploadInfo.token);
    formData.append('key', key);
    formData.append('file', {
      uri: uri,
      type: 'image/jpeg',
      name: 'image.jpg',
    });

    try {
      const response = await fetch('https://up-z2.qiniup.com', {
        method: 'POST',
        body: formData,
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });

      const result = await response.json();
      
      if (result.key) {
        return {
          success: true,
          imageUrl: `${this.uploadInfo.domain}/${result.key}`
        };
      }
      
      return { success: false, error: '上传失败' };
    } catch (error) {
      console.error('Upload error:', error);
      return { success: false, error: '上传过程中出错' };
    }
  }

  public async uploadImage(options = { multiple: false }): Promise<string[]> {
    try {
      // 检查权限
      const hasPermission = await this.checkPermission();
      if (!hasPermission) {
        return [];
      }

      // 获取七牛云上传凭证
      const hasToken = await this.getQiniuToken();
      if (!hasToken) {
        return [];
      }

      // 选择图片
      const result = await launchImageLibrary({
        mediaType: 'photo',
        quality: 1,
        selectionLimit: options.multiple ? 0 : 1,
      });

      if (result.didCancel || !result.assets) {
        return [];
      }

      // 上传所有选中的图片
      const uploadPromises = result.assets.map(async (asset) => {
        if (!asset.uri) return null;
        
        const key = this.generateKey();
        const uploadResult = await this.uploadToQiniu(asset.uri, key);
        
        if (uploadResult.success && uploadResult.imageUrl) {
          return uploadResult.imageUrl;
        }
        return null;
      });

      const results = await Promise.all(uploadPromises);
      const successUrls = results.filter((url): url is string => url !== null);

      if (successUrls.length > 0) {
        this.showToast('上传成功', 'success');
      } else {
        this.showToast('上传失败', 'error');
      }

      return successUrls;
    } catch (error) {
      console.error('Upload process error:', error);
      this.showToast('上传过程中出错', 'error');
      return [];
    }
  }
}

export const uploadImageService = UploadImageService.getInstance();