import 'dart:io';
import 'package:excel/excel.dart';
import 'package:path_provider/path_provider.dart';
import 'package:intl/intl.dart';

class ExcelExporter {
  static Future<String> exportPelangganToExcel(
      List<Map<String, dynamic>> data) async {
    final excel = Excel.createExcel();
    final sheet = excel['Data Pelanggan'];

    // Header kolom
    final headers = [
      TextCellValue('Nama Penerima'),
      TextCellValue('No. WA'),
      TextCellValue('Alamat'),
      TextCellValue('Kota'),
      TextCellValue('Provinsi'),
      TextCellValue('Barang'),
      TextCellValue('Total Nominal'),
      TextCellValue('Tanggal Dibuat'),
    ];
    sheet.appendRow(headers);

    final dateFormat = DateFormat('dd MMM yyyy, HH:mm', 'id_ID');

    // Isi data
    for (final item in data) {
      final createdAt = item['created_at'] != null
          ? dateFormat.format(item['created_at'])
          : '-';

      final row = [
        TextCellValue(item['penerima']?.toString() ?? '-'),
        TextCellValue(item['no_wa']?.toString() ?? '-'),
        TextCellValue(item['alamat']?.toString() ?? '-'),
        TextCellValue(item['kota']?.toString() ?? '-'),
        TextCellValue(item['provinsi']?.toString() ?? '-'),
        TextCellValue(item['barang']?.toString() ?? '-'),
        TextCellValue(item['totalNominal']?.toString() ?? '0'),
        TextCellValue(createdAt),
      ];

      sheet.appendRow(row);
    }

    // 🔹 Tentukan folder penyimpanan
    Directory? saveDir;

    if (Platform.isAndroid) {
      // Folder Download Android
      saveDir = Directory('/storage/emulated/0/Download');
    } else if (Platform.isWindows || Platform.isMacOS || Platform.isLinux) {
      // Folder Downloads desktop
      saveDir = await getDownloadsDirectory();
    } else if (Platform.isIOS) {
      // iOS tidak punya folder Download, pakai dokumen aplikasi
      saveDir = await getApplicationDocumentsDirectory();
    } else {
      throw Exception("Platform tidak didukung");
    }

    // 🔸 Pastikan folder valid dan ada
    if (saveDir == null) {
      throw Exception("Folder penyimpanan tidak ditemukan.");
    }

    if (!await saveDir.exists()) {
      await saveDir.create(recursive: true);
    }

    // 🔸 Nama file dengan timestamp
    final filePath =
        '${saveDir.path}/Data_Pelanggan_${DateFormat('yyyyMMdd_HHmmss').format(DateTime.now())}.xlsx';

    // Simpan file
    final bytes = excel.encode();
    final file = File(filePath);
    await file.writeAsBytes(bytes!, flush: true);

    return filePath;
  }
}
