import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:praresi/presentation/controllers/riwayat_controller.dart';
import 'package:praresi/utils/pdf_exporter.dart';

class DetailRiwayatView extends StatefulWidget {
  const DetailRiwayatView({super.key});

  @override
  State<DetailRiwayatView> createState() => _DetailRiwayatViewState();
}

class _DetailRiwayatViewState extends State<DetailRiwayatView> {
  final RiwayatController controller = Get.find<RiwayatController>();
  final TextEditingController searchController = TextEditingController();

  var filteredList = <Map<String, dynamic>>[].obs;

  @override
  void initState() {
    super.initState();

    final args = Get.arguments;
    final String date = args['date'];

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await controller
          .fetchResiByDate(DateFormat('d MMMM yyyy', 'id_ID').parse(date));

      filteredList.assignAll(controller.dailyDetail);
    });

    searchController.addListener(_filterData);
  }

  void _filterData() {
    final query = searchController.text.toLowerCase();
    if (query.isEmpty) {
      filteredList.assignAll(controller.dailyDetail);
    } else {
      filteredList.assignAll(
        controller.dailyDetail.where((item) {
          final nama = (item['penerima'] ?? '').toString().toLowerCase();
          return nama.contains(query);
        }).toList(),
      );
    }
  }

  @override
  void dispose() {
    searchController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final args = Get.arguments;
    final String day = args['day'];
    final String date = args['date'];

    return Scaffold(
      appBar: AppBar(
        title: Text(
          "$day, $date",
          style: const TextStyle(fontWeight: FontWeight.bold),
        ),
        backgroundColor: const Color(0xFF1976D2),
        foregroundColor: Colors.white,
      ),
      body: Obx(() {
        if (controller.isLoading.value) {
          return const Center(
            child: CircularProgressIndicator(color: Color(0xFF1976D2)),
          );
        }

        if (controller.dailyDetail.isEmpty) {
          return const Center(
            child: Text("Tidak ada data resi untuk hari ini"),
          );
        }

        return Column(
          children: [
            // 🔹 Search Bar
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              child: TextField(
                controller: searchController,
                decoration: InputDecoration(
                  hintText: 'Cari berdasarkan nama penerima...',
                  hintStyle: TextStyle(
                    color: Colors.grey[500],
                    fontSize: 14,
                    fontWeight: FontWeight.w400,
                  ),
                  prefixIcon: const Icon(
                    Icons.search_rounded,
                    color: Color(0xFF1976D2),
                    size: 22,
                  ),
                  filled: true,
                  fillColor: Colors.white,
                  contentPadding:
                      const EdgeInsets.symmetric(vertical: 14, horizontal: 16),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                    borderSide:
                        BorderSide(color: Colors.grey.shade200, width: 1),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                    borderSide:
                        const BorderSide(color: Color(0xFF1976D2), width: 1.5),
                  ),
                  suffixIcon: IconButton(
                    icon: const Icon(Icons.clear, color: Colors.grey, size: 20),
                    onPressed: () {
                      searchController.clear();
                    },
                  ),
                ),
                style: const TextStyle(
                  fontSize: 15,
                  color: Colors.black87,
                  fontWeight: FontWeight.w500,
                ),
                cursorColor: const Color(0xFF1976D2),
              ),
            ),

            // 🔹 Daftar hasil pencarian
            Expanded(
              child: Obx(() {
                if (filteredList.isEmpty) {
                  return const Center(
                    child: Text("Tidak ada hasil pencarian"),
                  );
                }

                return ListView.builder(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  itemCount: filteredList.length,
                  itemBuilder: (context, index) {
                    final item = filteredList[index];
                    final createdAt = item['created_at'] as DateTime;
                    final store = item['store'] ?? {};

                    return Card(
                      margin: const EdgeInsets.only(bottom: 16),
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12)),
                      elevation: 3,
                      child: Padding(
                        padding: const EdgeInsets.all(16),
                        child: Stack(
                          children: [
                            // 🔸 Isi utama kartu
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                const Text("📦 Detail Penerima",
                                    style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                        fontSize: 16)),
                                const SizedBox(height: 10),
                                _buildText("Penerima", item['penerima']),
                                _buildText("Barang", item['barang']),
                                _buildText("Alamat", item['alamat']),
                                _buildText("No. WA", item['no_wa']),
                                _buildText("Pembayaran", item['pembayaran']),
                                _buildText(
                                  "Total",
                                  "Rp ${NumberFormat('#,###', 'id_ID').format(num.tryParse(item['total'].toString()) ?? 0)}",
                                  isHighlight: true,
                                ),
                                _buildText(
                                  "Tanggal Dibuat",
                                  DateFormat('dd MMM yyyy, HH:mm', 'id_ID')
                                      .format(createdAt),
                                ),
                                const Divider(height: 24),
                                const Text("🏪 Pengirim",
                                    style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                        fontSize: 16)),
                                const SizedBox(height: 8),
                                _buildText("Nama Toko", store['namaToko']),
                                _buildText("No HP", store['noHp']),
                                _buildText(
                                    "No Registrasi", store['noRegistrasi']),
                                _buildText("Keterangan", store['keterangan']),
                              ],
                            ),

                            // 🔹 Tombol titik tiga (menu)
                            Positioned(
                              right: 0,
                              top: 0,
                              child: PopupMenuButton<String>(
                                onSelected: (value) async {
                                  if (value == 'edit') {
                                    _onEdit(item);
                                  } else if (value == 'hapus') {
                                    _onDelete(controller, item['id']);
                                  } else if (value == 'cetak') {
                                    _onPrint(item);
                                  }
                                },
                                itemBuilder: (context) => [
                                  const PopupMenuItem(
                                    value: 'edit',
                                    child: Row(
                                      children: [
                                        Icon(Icons.edit, color: Colors.blue),
                                        SizedBox(width: 8),
                                        Text("Edit"),
                                      ],
                                    ),
                                  ),
                                  const PopupMenuItem(
                                    value: 'hapus',
                                    child: Row(
                                      children: [
                                        Icon(Icons.delete, color: Colors.red),
                                        SizedBox(width: 8),
                                        Text("Hapus"),
                                      ],
                                    ),
                                  ),
                                  const PopupMenuItem(
                                    value: 'cetak',
                                    child: Row(
                                      children: [
                                        Icon(Icons.download,
                                            color: Colors.green),
                                        SizedBox(width: 8),
                                        Text("Unduh"),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                );
              }),
            ),
          ],
        );
      }),
    );
  }

  Widget _buildText(String title, String? value, {bool isHighlight = false}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(flex: 3, child: Text("$title:")),
          Expanded(
            flex: 5,
            child: Text(
              value ?? '-',
              style: TextStyle(
                color: isHighlight ? Colors.green : Colors.black,
                fontWeight: isHighlight ? FontWeight.bold : FontWeight.normal,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 🔹 Fungsi aksi tombol titik tiga
void _onEdit(Map<String, dynamic> item) {
  final TextEditingController penerimaController =
      TextEditingController(text: item['penerima'] ?? '');
  final TextEditingController barangController =
      TextEditingController(text: item['barang'] ?? '');
  final TextEditingController alamatController =
      TextEditingController(text: item['alamat'] ?? '');
  final TextEditingController noWaController =
      TextEditingController(text: item['no_wa'] ?? '');
  final TextEditingController pembayaranController =
      TextEditingController(text: item['pembayaran'] ?? '');
  final TextEditingController totalController =
      TextEditingController(text: item['total']?.toString() ?? '');

  Get.defaultDialog(
    title: "Edit Data Penerima",
    radius: 10,
    content: ConstrainedBox(
      constraints: const BoxConstraints(
        maxHeight: 300, // 👈 batasi tinggi agar dialog bisa discroll
      ),
      child: SingleChildScrollView(
        child: Column(
          children: [
            _buildEditField("Nama Penerima", penerimaController),
            _buildEditField("Nama Barang", barangController),
            _buildEditField("Alamat", alamatController),
            _buildEditField("No. WA", noWaController),
            _buildEditField("Pembayaran",pembayaranController,isDropdown: true,),
            _buildEditField("Total (Rp)", totalController,
                inputType: TextInputType.number),
            const SizedBox(height: 20),
            ElevatedButton.icon(
              onPressed: () async {
                // 🔹 Validasi input sederhana
                if (penerimaController.text.isEmpty ||
                    barangController.text.isEmpty ||
                    alamatController.text.isEmpty) {
                  Get.snackbar("Gagal", "Pastikan semua data terisi",
                      backgroundColor: Colors.red.shade100,
                      snackPosition: SnackPosition.BOTTOM);
                  return;
                }

                try {
                  await controller.updateResi(item['id'], {
                    'penerima': penerimaController.text,
                    'barang': barangController.text,
                    'alamat': alamatController.text,
                    'no_wa': noWaController.text,
                    'pembayaran': pembayaranController.text,
                    'total': totalController.text,
                  });

                  Get.back(); // Tutup dialog
                  Get.snackbar("Berhasil", "Data berhasil diperbarui",
                      backgroundColor: Colors.green.shade100,
                      snackPosition: SnackPosition.BOTTOM);
                } catch (e) {
                  Get.snackbar("Error", "Gagal memperbarui data: $e",
                      backgroundColor: Colors.red.shade100,
                      snackPosition: SnackPosition.BOTTOM);
                }
              },
              icon: const Icon(Icons.save),
              label: const Text("Simpan Perubahan"),
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFF1976D2),
                foregroundColor: Colors.white,
                minimumSize: const Size(double.infinity, 45),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
            ),
          ],
        ),
      ),
    ),
  );
}


// Widget _buildEditField(String label, TextEditingController controller,
//     {TextInputType inputType = TextInputType.text}) {
//   return Padding(
//     padding: const EdgeInsets.only(bottom: 12),
//     child: TextField(
//       controller: controller,
//       keyboardType: inputType,
//       decoration: InputDecoration(
//         labelText: label,
//         labelStyle:
//             const TextStyle(color: Colors.black54, fontWeight: FontWeight.w500),
//         border: OutlineInputBorder(
//           borderRadius: BorderRadius.circular(8),
//         ),
//         focusedBorder: const OutlineInputBorder(
//           borderSide: BorderSide(color: Color(0xFF1976D2), width: 1.5),
//         ),
//       ),
//     ),
//   );
// }

Widget _buildEditField(
  String label,
  TextEditingController controller, {
  TextInputType inputType = TextInputType.text,
  bool isDropdown = false,
}) {
  return Padding(
    padding: const EdgeInsets.only(bottom: 12),
    child: TextField(
      controller: controller,
      keyboardType: inputType,
      readOnly: isDropdown, // 🔥 penting
      onTap: isDropdown
          ? () async {
              final selected = await showModalBottomSheet<String>(
                context: Get.context!,
                builder: (context) {
                  return SafeArea(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        ListTile(
                          title: const Text("COD"),
                          onTap: () => Navigator.pop(context, "COD"),
                        ),
                        ListTile(
                          title: const Text("NON COD"),
                          onTap: () => Navigator.pop(context, "NON COD"),
                        ),
                      ],
                    ),
                  );
                },
              );

              if (selected != null) {
                controller.text = selected;
              }
            }
          : null,
      decoration: InputDecoration(
        labelText: label,
        labelStyle: const TextStyle(
          color: Colors.black54,
          fontWeight: FontWeight.w500,
        ),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
        ),
        focusedBorder: const OutlineInputBorder(
          borderSide: BorderSide(color: Color(0xFF1976D2), width: 1.5),
        ),
        suffixIcon: isDropdown
            ? const Icon(Icons.arrow_drop_down) // 🔥 biar keliatan dropdown
            : null,
      ),
    ),
  );
}


  void _onDelete(RiwayatController controller, String id) async {
  final confirm = await Get.defaultDialog<bool>(
    title: "Hapus Data",
    middleText: "Apakah kamu yakin ingin menghapus data ini?",
    textCancel: "Batal",
    textConfirm: "Hapus",
    confirmTextColor: Colors.white,
    onConfirm: () => Get.back(result: true),
    onCancel: () => Get.back(result: false),
  );

  if (confirm == true) {
    await controller.deleteResi(id);
  }
}


  void _onPrint(Map<String, dynamic> item) async {
  try {
    // Ambil tanggal untuk tampilan info di PDF
    final createdAt = item['created_at'] ?? DateTime.now();
    final day = DateFormat.EEEE('id_ID').format(createdAt);
    final date = DateFormat('d MMMM yyyy', 'id_ID').format(createdAt);

    // Ambil controller Analisis (kalau dibutuhkan)
    final controller = Get.find<RiwayatController>();

    // 🔹 Tampilkan dialog pemilihan format
    _showPrintFormatDialog(Get.context!, day, date, item, controller);
  } catch (e) {
    Get.snackbar(
      "Error",
      "Gagal memproses cetak: $e",
      snackPosition: SnackPosition.BOTTOM,
      backgroundColor: Colors.red.shade100,
    );
  }
}


void _showPrintFormatDialog(
  BuildContext context,
  String day,
  String date,
  Map<String, dynamic> item,
  dynamic controller,
) {
  Get.bottomSheet(
    Container(
      padding: const EdgeInsets.all(20),
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      child: Wrap(
        children: [
          const Center(
            child: Text(
              "Pilih Format Unduh",
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
          ),
          const SizedBox(height: 20),

          // 🔹 FORMAT A4
          ListTile(
            leading: const Icon(Icons.picture_as_pdf, color: Colors.blue),
            title: const Text("Format A4"),
            onTap: () async {
              Get.back();
              try {
                final path = await PdfExporter.exportSingleItemToPdf(
                  item,
                  format: 'A4',
                );

                Get.snackbar(
                  "Berhasil",
                  "PDF disimpan di: $path",
                  snackPosition: SnackPosition.BOTTOM,
                  backgroundColor: Colors.green.shade100,
                );
              } catch (e) {
                Get.snackbar(
                  "Error",
                  "Gagal mencetak data: $e",
                  snackPosition: SnackPosition.BOTTOM,
                  backgroundColor: Colors.red.shade100,
                );
              }
            },
          ),

          // 🔹 FORMAT A5
          ListTile(
            leading: const Icon(Icons.picture_as_pdf, color: Colors.blue),
            title: const Text("Format A5"),
            onTap: () async {
              Get.back();
              try {
                final path = await PdfExporter.exportSingleItemToPdf(
                  item,
                  format: 'A5',
                );

                Get.snackbar(
                  "Berhasil",
                  "PDF disimpan di: $path",
                  snackPosition: SnackPosition.BOTTOM,
                  backgroundColor: Colors.green.shade100,
                );
              } catch (e) {
                Get.snackbar(
                  "Error",
                  "Gagal mencetak data: $e",
                  snackPosition: SnackPosition.BOTTOM,
                  backgroundColor: Colors.red.shade100,
                );
              }
            },
          ),

          // 🔹 FORMAT A6
          ListTile(
            leading: const Icon(Icons.picture_as_pdf, color: Colors.blue),
            title: const Text("Format A6"),
            onTap: () async {
              Get.back();
              try {
                final path = await PdfExporter.exportSingleItemToPdf(
                  item,
                  format: 'A6',
                );

                Get.snackbar(
                  "Berhasil",
                  "PDF disimpan di: $path",
                  snackPosition: SnackPosition.BOTTOM,
                  backgroundColor: Colors.green.shade100,
                );
              } catch (e) {
                Get.snackbar(
                  "Error",
                  "Gagal mencetak data: $e",
                  snackPosition: SnackPosition.BOTTOM,
                  backgroundColor: Colors.red.shade100,
                );
              }
            },
          ),
        ],
      ),
    ),
  );
}


}
