import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:file_picker/file_picker.dart';

class FileDownloader {
  static Future<String?> downloadAndSave({
    required String url,
    required String fileName,
    void Function(int received, int total)? onProgress,
  }) async {
    final dio = Dio();

    final response = await dio.get<List<int>>(
      url,
      options: Options(responseType: ResponseType.bytes),
      onReceiveProgress: onProgress,
    );

    final bytes = response.data;

    if (bytes == null) return null;

    final savedPath = await FilePicker.saveFile(
      dialogTitle: 'Save File',
      fileName: fileName,
      type: FileType.custom,
      allowedExtensions: ['pdf'],
      bytes: Uint8List.fromList(bytes),
    );

    return savedPath;
  }

  static Future<Map<String, dynamic>> getFileInfo(String url) async {
    final dio = Dio();

    final response = await dio.head<dynamic>(url);
    final headers = response.headers;
    final size = headers.value('content-length');
    final sizeInBytes = int.tryParse(size ?? '0') ?? 0;
    final sizeInMB = sizeInBytes / (1024 * 1024);
    var fileName = url.split('/').last;
    final disposition = headers.value('content-disposition');

    if (disposition != null && disposition.contains('filename=')) {
      fileName = disposition.split('filename=').last.replaceAll('"', '');
    }

    return {
      'name': fileName,
      'sizeMB': sizeInMB,
      'sizeBytes': sizeInBytes,
    };
  }
}
