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

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

  @override
  State<DataPelangganView> createState() => _DataPelangganViewState();
}

class _DataPelangganViewState extends State<DataPelangganView> {
  final PelangganController controller = Get.put(PelangganController());
  final TextEditingController searchController = TextEditingController();
  var filteredList = <Map<String, dynamic>>[].obs;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      filteredList.assignAll(controller.pelangganList);
      controller.pelangganList.listen((_) {
        filteredList.assignAll(controller.pelangganList);
      });
    });
    searchController.addListener(_filterData);
  }

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

  Future<void> exportToExcel() async {
  try {
    final path = await ExcelExporter.exportPelangganToExcel(
      controller.pelangganList.toList(),
    );
    Get.snackbar(
      "Berhasil",
      "File diekspor ke: $path",
      backgroundColor: Colors.green.shade50,
      colorText: Colors.black,
      duration: const Duration(seconds: 5),
    );
  } catch (e) {
    Get.snackbar(
      "Gagal",
      "Terjadi kesalahan saat mengekspor: $e",
      backgroundColor: Colors.red.shade50,
      colorText: Colors.black,
    );
  }
}



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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          "Data Pelanggan",
          style: TextStyle(fontWeight: FontWeight.bold, color: Colors.white),
          
        ),
        centerTitle: true,
        backgroundColor: const Color(0xFF1976D2),
        foregroundColor: Colors.white,
        actions: [
          PopupMenuButton<String>(
            icon: const Icon(Icons.more_vert),
            onSelected: (value) {
              if (value == 'unduh') {
                exportToExcel();
              } else if (value == 'refresh') {
                controller.fetchAllPelanggan();
              }
            },
            itemBuilder: (context) => [
              const PopupMenuItem(
                value: 'unduh',
                child: Row(
                  children: [
                    Icon(Icons.download, color: Colors.blue),
                    SizedBox(width: 10),
                    Text("Unduh Data Pelanggan"),
                  ],
                ),
              ),
              const PopupMenuItem(
                value: 'refresh',
                child: Row(
                  children: [
                    Icon(Icons.refresh, color: Colors.green),
                    SizedBox(width: 10),
                    Text("Muat Ulang Data"),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
      body: Obx(() {
        if (controller.isLoading.value) {
          return const Center(
            child: CircularProgressIndicator(color: Color(0xFF1976D2)),
          );
        }

        return Column(
          children: [
            // 🔹 Statistik jumlah pelanggan
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(16),
              color: Colors.blue.shade50,
              child: Text(
                "Total Pelanggan: ${controller.totalPelanggan.value}",
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: Color(0xFF1976D2),
                ),
              ),
            ),

            // 🔹 Search Bar
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              child: TextField(
                controller: searchController,
                decoration: InputDecoration(
                  hintText: 'Cari berdasarkan nama pelanggan...',
                  prefixIcon: const Icon(Icons.search_rounded,
                      color: Color(0xFF1976D2)),
                  filled: true,
                  fillColor: Colors.white,
                  contentPadding:
                      const EdgeInsets.symmetric(vertical: 14, horizontal: 16),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                    borderSide:
                        BorderSide(color: Colors.grey.shade300, width: 1),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                    borderSide:
                        const BorderSide(color: Color(0xFF1976D2), width: 1.5),
                  ),
                ),
                cursorColor: const Color(0xFF1976D2),
              ),
            ),

            // 🔹 Daftar Pelanggan
            Expanded(
              child: Obx(() {
                if (filteredList.isEmpty) {
                  return const Center(child: Text("Tidak ada data pelanggan"));
                }

                return ListView.builder(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  itemCount: filteredList.length,
                  itemBuilder: (context, index) {
                    final item = filteredList[index];

                    // Format tanggal
                    final createdAt = item['created_at'] != null
                        ? DateFormat('dd MMM yyyy, HH:mm', 'id_ID')
                            .format(item['created_at'])
                        : '-';

                    return Card(
                      margin: const EdgeInsets.only(bottom: 12),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                      elevation: 3,
                      child: Padding(
                        padding: const EdgeInsets.all(16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              item['penerima'] ?? '-',
                              style: const TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: Color(0xFF1976D2),
                              ),
                            ),
                            const SizedBox(height: 8),
                            _buildText("No. WA", item['no_wa']),
                            _buildText("Alamat", item['alamat']),
                            _buildText("Kota", item['kota']),
                            _buildText("Provinsi", item['provinsi']),
                            _buildText("Barang", item['barang']),
                            _buildText(
                              "Total Nominal",
                              "Rp ${NumberFormat('#,###', 'id_ID').format(item['totalNominal'] ?? 0)}",
                              isHighlight: true,
                            ),
                            const SizedBox(height: 6),
                            _buildText("Tanggal Dibuat", createdAt),
                          ],
                        ),
                      ),
                    );
                  },
                );
              }),
            ),
          ],
        );
      }),
    );
  }

  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,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
