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 PdfExportDailyA4_onedata {
  /// Cetak seluruh data resi dalam 1 hari ke format A4 (1 resi per halaman)
  static Future<String> exportDailyToA4_onedata(
    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.a4,
          margin: const pw.EdgeInsets.all(30),
          build: (pw.Context context) {
            return pw.Column(
              crossAxisAlignment: pw.CrossAxisAlignment.start,
              children: [

                /// HEADER
                pw.Row(
                  mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
                  children: [
                    pw.Text(
                      'DATA PENGIRIMAN #${i + 1}',
                      style: pw.TextStyle(
                        fontWeight: pw.FontWeight.bold,
                        fontSize: 18,
                      ),
                    ),
                    pw.Text(
                      createdAt,
                      style: const pw.TextStyle(fontSize: 12),
                    ),
                  ],
                ),

                pw.SizedBox(height: 10),
                pw.Divider(),

                /// DATA PENERIMA
                _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: 20),

                /// DATA TOKO
                pw.Text(
                  'DATA TOKO PENGIRIM',
                  style: pw.TextStyle(
                    fontWeight: pw.FontWeight.bold,
                    fontSize: 16,
                  ),
                ),

                pw.Divider(),

                _buildRow('Nama Toko', namaToko),
                _buildRow('Alamat Toko', alamatToko),
                _buildRow('No. HP Toko', noHpToko),
                _buildRow('No. Registrasi', noRegistrasi),
                _buildRow('Keterangan', keteranganToko),

                pw.Spacer(),

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

    /// Simpan file
    Directory? downloadDir;

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

    final filePath =
        '${downloadDir.path}/Resi_Harian_A4_${DateFormat('yyyyMMdd_HHmmss').format(DateTime.now())}.pdf';

    final file = File(filePath);
    await file.writeAsBytes(await pdf.save());

    return filePath;
  }

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