import 'dart:io';
import 'package:intl/intl.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;

class PdfExportDailyA6 {
  /// Cetak seluruh data resi dalam 1 hari ke format A6 (1 resi per halaman)
  static Future<String> exportDailyToA6(
    List<Map<String, dynamic>> items,
    DateTime selectedDate,
  ) async {
    final pdf = pw.Document();
    final dateFormat = DateFormat('dd MMM yyyy, HH:mm', 'id_ID');

    for (var i = 0; i < items.length; i++) {
      final item = items[i];

      final createdAt = item['created_at'] != null
          ? dateFormat.format(item['created_at'])
          : '-';

      final totalNominal =
          num.tryParse(item['total']?.toString() ?? '0') ?? 0;

      final store = item['store'] ?? {};
      final namaToko = store['namaToko'] ?? '-';
      final alamatToko = store['alamat'] ?? '-';
      final noHpToko = store['noHp'] ?? '-';
      final noRegistrasi = store['noRegistrasi'] ?? '-';
      final keteranganToko = store['keterangan'] ?? '-';

      pdf.addPage(
        pw.Page(
          pageFormat: PdfPageFormat.a6,
          margin: const pw.EdgeInsets.all(10),
          build: (pw.Context context) {
            return pw.Column(
              crossAxisAlignment: pw.CrossAxisAlignment.start,
              children: [
                pw.Row(
                  mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
                  children: [
                    pw.Text(
                      'DATA PENGIRIMAN #${i + 1}',
                      style: pw.TextStyle(
                        fontWeight: pw.FontWeight.bold,
                        fontSize: 8.5,
                      ),
                    ),
                    pw.Text(
                      createdAt,
                      style: const pw.TextStyle(fontSize: 7),
                    ),
                  ],
                ),
                pw.Divider(thickness: 0.5),
                _buildRow('Nama Penerima', item['penerima']),
                _buildRow('No. WA', item['no_wa']),
                _buildRow('Alamat', item['alamat']),
                _buildRow('Kota', item['kota']),
                _buildRow('Provinsi', item['provinsi']),
                _buildRow('Barang', item['barang']),
                _buildRow(
                  'Total Nominal',
                  'Rp ${NumberFormat('#,##0', 'id_ID').format(totalNominal)}',
                ),
                _buildRow('Pembayaran', item['pembayaran']),
                pw.SizedBox(height: 3),
                pw.Text(
                  'DATA TOKO PENGIRIM',
                  style: pw.TextStyle(
                    fontWeight: pw.FontWeight.bold,
                    fontSize: 8,
                  ),
                ),
                pw.Divider(thickness: 0.5),
                _buildRow('Nama Toko', namaToko),
                _buildRow('Alamat Toko', alamatToko),
                _buildRow('No. HP Toko', noHpToko),
                _buildRow('No. Registrasi', noRegistrasi),
                _buildRow('Keterangan', keteranganToko),
                pw.Spacer(),
                pw.Center(
                  child: pw.Text(
                    'Dicetak otomatis oleh sistem Praresi',
                    style: const pw.TextStyle(fontSize: 7),
                  ),
                ),
              ],
            );
          },
        ),
      );
    }

    // 🔹 Simpan ke folder Download
    Directory? downloadDir;
    if (Platform.isAndroid) {
      downloadDir = Directory('/storage/emulated/0/Download');
    } else {
      downloadDir = await getApplicationDocumentsDirectory();
    }

    final filePath =
        '${downloadDir.path}/Resi_Harian_A6_${DateFormat('yyyyMMdd_HHmmss').format(DateTime.now())}.pdf';
    final file = File(filePath);
    await file.writeAsBytes(await pdf.save());

    return filePath;
  }

  /// 🔹 Komponen pembantu untuk membuat baris label : value
  static pw.Widget _buildRow(String label, dynamic value) {
    return pw.Padding(
      padding: const pw.EdgeInsets.symmetric(vertical: 0.5),
      child: pw.Row(
        crossAxisAlignment: pw.CrossAxisAlignment.start,
        children: [
          pw.Container(
            width: 75,
            child: pw.Text(
              label,
              style: pw.TextStyle(
                fontWeight: pw.FontWeight.bold,
                fontSize: 7.2,
              ),
            ),
          ),
          pw.Expanded(
            child: pw.Text(
              value?.toString() ?? '-',
              style: const pw.TextStyle(fontSize: 7.2),
            ),
          ),
        ],
      ),
    );
  }
}
