import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:pharmacy_mobile/widgets/snackbar_widget.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

class Storage {
  final SupabaseClient _supabase = Supabase.instance.client;

  Future<String> createBucket(String name) async {
    try {
      final response = await _supabase.storage.createBucket(name);
      return response;
    } catch (e, stackTrace) {
      log('Error creating bucket: $e', stackTrace: stackTrace);
      rethrow;
    }
  }

  Future<List> getList() async {
    try {
      final response = await _supabase.storage.listBuckets();
      return response;
    } catch (e, stackTrace) {
      log('Error getting list: $e', stackTrace: stackTrace);
      rethrow;
    }
  }

  Future<void> uploadFile(XFile image, String name) async {
    try {
      final imageString = await image.readAsString(encoding: utf8);
      final imageFile = File(imageString);
      await _supabase.storage.from('images').upload(name, imageFile);
      log('upload Complete');
    } catch (e) {
      log('Error getting list: $e');
      rethrow;
    }
  }

  Future<String> uploadImage(BuildContext context, String storage, Uint8List image, String name) async {
    try {
      final imageBytes = image;
      final imagePath = name;

      await _supabase.storage.from(storage).uploadBinary(imagePath, imageBytes);
      final imageUrl = _supabase.storage.from(storage).getPublicUrl(imagePath);
      return imageUrl;
    } catch (e) {
      // ignore: use_build_context_synchronously
      showNotification(context, 'Error uploading image: $e', false);
      rethrow;
    }
  }

  Future<Uint8List> downloadImage(String storage, String name) async {
    final Uint8List file = await _supabase.storage.from(storage).download(name);
    return file;
  }

  Future<String> getPublicURL(String storage, String name) async {
    final String file = _supabase.storage.from(storage).getPublicUrl(name);
    return file;
  }
}
