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 PdfExportDailyA5 {
  /// Cetak seluruh data resi dalam 1 hari ke format A5 (maks 3 resi per halaman)
  static Future<String> exportDailyToA5(
    List<Map<String, dynamic>> items,
    DateTime selectedDate,
  ) async {
    final pdf = pw.Document();
    final dateFormat = DateFormat('dd MMM yyyy, HH:mm', 'id_ID');

    // 🔹 Bagi data menjadi grup per 3 item
    final chunkedItems = <List<Map<String, dynamic>>>[];
    for (var i = 0; i < items.length; i += 3) {
      chunkedItems.add(items.skip(i).take(3).toList());
    }

    for (final pageItems in chunkedItems) {
      pdf.addPage(
        pw.Page(
          pageFormat: PdfPageFormat.a5,
          margin: const pw.EdgeInsets.all(12),
          build: (pw.Context context) {
            return pw.Column(
              crossAxisAlignment: pw.CrossAxisAlignment.start,
              children: [
                ...pageItems.asMap().entries.map((entry) {
                  final index = entry.key + 1;
                  final item = entry.value;

                  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'] ?? '-';

                  return pw.Container(
                    margin: const pw.EdgeInsets.only(bottom: 6),
                    padding: const pw.EdgeInsets.all(5),
                    decoration: pw.BoxDecoration(
                      border: pw.Border.all(color: PdfColors.grey700, width: 0.6),
                      borderRadius: pw.BorderRadius.circular(4),
                    ),
                    child: pw.Column(
                      crossAxisAlignment: pw.CrossAxisAlignment.start,
                      children: [
                        pw.Row(
                          mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
                          children: [
                            pw.Text(
                              'DATA PENGIRIMAN #$index',
                              style: pw.TextStyle(
                                fontWeight: pw.FontWeight.bold,
                                fontSize: 9,
                              ),
                            ),
                            pw.Text(
                              createdAt,
                              style: const pw.TextStyle(fontSize: 7.5),
                            ),
                          ],
                        ),
                        pw.SizedBox(height: 3),
                        _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.5,
                          ),
                        ),
                        pw.SizedBox(height: 2),
                        _buildRow('Nama Toko', namaToko),
                        _buildRow('Alamat Toko', alamatToko),
                        _buildRow('No. HP Toko', noHpToko),
                        _buildRow('No. Registrasi', noRegistrasi),
                        _buildRow('Keterangan', keteranganToko),
                      ],
                    ),
                  );
                }).toList(),

                pw.Spacer(),
                pw.Center(
                  child: pw.Text(
                    'Dicetak otomatis oleh sistem Praresi',
                    style: const pw.TextStyle(fontSize: 7.5),
                  ),
                ),
              ],
            );
          },
        ),
      );
    }

    // 🔹 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_A5_${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.6),
      child: pw.Row(
        crossAxisAlignment: pw.CrossAxisAlignment.start,
        children: [
          pw.Container(
            width: 80,
            child: pw.Text(
              label,
              style: pw.TextStyle(
                fontWeight: pw.FontWeight.bold,
                fontSize: 7.8,
              ),
            ),
          ),
          pw.Expanded(
            child: pw.Text(
              value?.toString() ?? '-',
              style: const pw.TextStyle(fontSize: 7.8),
            ),
          ),
        ],
      ),
    );
  }
}
