import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';

import '../api/pocketbase_client.dart';
import '../../models/job_file.dart';
import '../theme/app_theme.dart';

class FileDownloadHelper {
  static Future<void> download(BuildContext context, JobFile file, {Rect? shareOrigin}) async {
    if (file.downloadUrl.isEmpty) return;
    final messenger = ScaffoldMessenger.of(context);
    try {
      final pb = PocketBaseClient.instance.pb;
      final fileToken = await pb.files.getToken();
      final uri = Uri.parse('${file.downloadUrl}?token=$fileToken');
      final response = await http.get(uri);
      if (response.statusCode != 200) throw Exception('HTTP ${response.statusCode}');
      final dir = await getTemporaryDirectory();
      final path = '${dir.path}/${file.name}';
      await File(path).writeAsBytes(response.bodyBytes);
      await Share.shareXFiles(
        [XFile(path, mimeType: file.mimeType ?? 'application/octet-stream')],
        subject: file.name,
        sharePositionOrigin: shareOrigin ?? const Rect.fromLTWH(0, 0, 1, 1),
      );
    } catch (e) {
      if (context.mounted) {
        messenger.showSnackBar(
          SnackBar(
            content: Text('İndirilemedi: $e'),
            backgroundColor: AppColors.cancelled,
          ),
        );
      }
    }
  }
}
