import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:praresi/presentation/controllers/riwayat_bulanan_controller.dart';

class RiwayatBulananDetailView extends StatefulWidget {
  final String month;
  const RiwayatBulananDetailView({super.key, required this.month});

  @override
  State<RiwayatBulananDetailView> createState() =>
      _RiwayatBulananDetailViewState();
}

class _RiwayatBulananDetailViewState extends State<RiwayatBulananDetailView> {
  final RiwayatBulananController controller =
      Get.find<RiwayatBulananController>();
  final TextEditingController searchController = TextEditingController();

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

  @override
  void initState() {
    super.initState();
    _loadData();
    searchController.addListener(_filterData);
  }

  Future<void> _loadData() async {
    final data = await controller.fetchResiByMonth(widget.month);
    filteredList.assignAll(data);
  }

  void _filterData() {
    final query = searchController.text.toLowerCase();
    if (query.isEmpty) {
      _loadData();
    } else {
      filteredList.assignAll(
        filteredList.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) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "Riwayat ${widget.month}",
          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 (filteredList.isEmpty) {
          return const Center(
            child: Text("Tidak ada data resi untuk bulan 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...',
                  prefixIcon:
                      const Icon(Icons.search, 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.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();
                    },
                  ),
                ),
              ),
            ),

            // 🔹 List data penerima
            Expanded(
              child: ListView.builder(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                itemCount: filteredList.length,
                itemBuilder: (context, index) {
                  final item = filteredList[index];
                  final createdAt = item['created_at'] is DateTime
                      ? item['created_at'] as DateTime
                      : (item['created_at']?.toDate() ?? DateTime.now());
                  final total = num.tryParse(item['total'].toString()) ?? 0;

                  return Card(
                    margin: const EdgeInsets.only(bottom: 16),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12)),
                    elevation: 3,
                    child: Padding(
                      padding: const EdgeInsets.all(16),
                      child: 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(total)}",
                            isHighlight: true,
                          ),
                          _buildText(
                            "Tanggal Dibuat",
                            DateFormat('dd MMM yyyy, HH:mm', 'id_ID')
                                .format(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,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
