import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/extensions/num_extension.dart';
import 'package:mypoint_flutter_app/widgets/custom_empty_widget.dart';
import '../../resources/base_color.dart';
import '../../shared/router_gage.dart';
import '../../widgets/custom_navigation_bar.dart';
import 'models/customer_contract_object_model.dart';
import 'electric_payment_bill_screen.dart';
import 'electric_payment_viewmodel.dart';

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

  @override
  State<ElectricPaymentHistoryScreen> createState() => _ElectricPaymentHistoryScreenState();
}

class _ElectricPaymentHistoryScreenState extends State<ElectricPaymentHistoryScreen> {
  final ElectricPaymentViewModel _viewModel = Get.put(ElectricPaymentViewModel());
  bool isEditMode = false;
  bool selectAll = false;
  List<String> selectedCodes = [];

  void toggleEditMode() {
    if (_viewModel.billContracts.value.isEmpty) return;
    setState(() {
      isEditMode = !isEditMode;
      selectedCodes.clear();
      selectAll = false;
    });
  }

  void toggleSelectAll(bool? value) {
    setState(() {
      selectAll = value ?? false;
      if (selectAll) {
        final codes = _viewModel.billContracts.value.map((e) => e.maKH ?? '').where((e) => e.isNotEmpty).toList();
        selectedCodes = codes.cast<String>();
      } else {
        selectedCodes.clear();
      }
    });
  }

  void toggleItem(CustomerContractModel data, bool? value) {
    setState(() {
      if (value ?? false) {
        selectedCodes.add(data.maKH ?? '');
      } else {
        selectedCodes.remove(data.maKH ?? '');
        selectAll = false;
      }
    });
  }

  void deleteSelected() {
    if (selectedCodes.isEmpty) return;
    setState(() {
      _viewModel.customerContractDelete(selectedCodes.join(','));
      isEditMode = false;
      selectedCodes.clear();
      selectAll = false;
    });
  }

  @override
  void initState() {
    super.initState();
    _viewModel.customerContractSearchHistoryGetList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomNavigationBar(title: 'Hoá đơn điện'),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(20),
            child: SizedBox(
              width: double.infinity,
              child: ElevatedButton.icon(
                style: ElevatedButton.styleFrom(
                  backgroundColor: BaseColor.primary500,
                  minimumSize: const Size(double.infinity, 48),
                ),
                icon: const Icon(Icons.add, color: Colors.white),
                label: const Text(
                  'Thêm hóa đơn mới',
                  style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
                ),
                onPressed: () async {
                  await Get.toNamed(electricPaymentScreen);
                  _viewModel.customerContractSearchHistoryGetList();
                },
              ),
            ),
          ),
          Container(height: 12, color: BaseColor.second100),
          const SizedBox(height: 24),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Row(
              children: [
                const Expanded(child: Text('Lịch sử', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold))),
                GestureDetector(
                  onTap: toggleEditMode,
                  child: Text(isEditMode ? 'Hủy' : 'Sửa', style: const TextStyle(color: Colors.blue)),
                ),
              ],
            ),
          ),
          const SizedBox(height: 8),
          Obx(() {
            return (_viewModel.billContracts.value.isEmpty)
                ? Expanded(child: Center(child: EmptyWidget()))
                : Expanded(
                  child: ListView.builder(
                    itemCount: _viewModel.billContracts.value.length,
                    itemBuilder: (context, index) {
                      final bill = _viewModel.billContracts.value[index];
                      final isSelected = selectedCodes.contains(bill.maKH ?? '');
                      return Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
                        child: Container(
                          decoration: BoxDecoration(
                            color: Colors.grey.shade100,
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Padding(
                            padding: const EdgeInsets.symmetric(vertical: 8),
                            child: Container(
                              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                              decoration: BoxDecoration(
                                color: Colors.grey.shade100,
                                borderRadius: BorderRadius.circular(8),
                              ),
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  if (isEditMode)
                                    Padding(
                                      padding: const EdgeInsets.only(right: 8),
                                      child: Checkbox(value: isSelected, onChanged: (val) => toggleItem(bill, val)),
                                    ),
                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text(bill.location ?? '', style: const TextStyle(fontWeight: FontWeight.w600)),
                                        const SizedBox(height: 6),
                                        if ((bill.maKH ?? '').isNotEmpty) Text(bill.maKH ?? ''),
                                        const SizedBox(height: 6),
                                        if ((bill.nameKH ?? '').isNotEmpty) Text(bill.nameKH ?? ''),
                                      ],
                                    ),
                                  ),
                                  const SizedBox(width: 12),
                                  ConstrainedBox(
                                    constraints: const BoxConstraints(minWidth: 100, maxWidth: 140),
                                    child:
                                        (bill.amount ?? 0) == 0
                                            ? Column(
                                              mainAxisAlignment: MainAxisAlignment.center,
                                              crossAxisAlignment: CrossAxisAlignment.end,
                                              children: const [
                                                Icon(Icons.check_circle, color: Colors.green),
                                                SizedBox(height: 4),
                                                Text(
                                                  'Bạn đã hết nợ cước',
                                                  style: TextStyle(fontSize: 12, color: Colors.green),
                                                ),
                                              ],
                                            )
                                            : Column(
                                              mainAxisAlignment: MainAxisAlignment.center,
                                              crossAxisAlignment: CrossAxisAlignment.end,
                                              children: [
                                                Text(
                                                  (bill.amount ?? 0).money(CurrencyUnit.VND),
                                                  style: const TextStyle(
                                                    fontSize: 14,
                                                    color: Colors.black87,
                                                    fontWeight: FontWeight.bold,
                                                  ),
                                                ),
                                                const SizedBox(height: 8),
                                                GestureDetector(
                                                  onTap: () {
                                                    Get.to(ElectricPaymentBillScreen(bill: bill,));
                                                    debugPrint('Thanh toán hoá đơn: ${bill.maKH ?? ''}');
                                                  },
                                                  child: Container(
                                                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                                                    decoration: BoxDecoration(
                                                      color: BaseColor.primary500,
                                                      borderRadius: BorderRadius.circular(12),
                                                    ),
                                                    child: const Text(
                                                      'Thanh toán',
                                                      style: TextStyle(
                                                        fontSize: 14,
                                                        color: Colors.white,
                                                        fontWeight: FontWeight.bold,
                                                      ),
                                                    ),
                                                  ),
                                                ),
                                              ],
                                            ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                );
          }),
        ],
      ),
      bottomNavigationBar: isEditMode ? _buildBottomButtonEditMode() : null,
    );
  }

  Widget _buildBottomButtonEditMode() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
      decoration: const BoxDecoration(
        color: Colors.white,
        boxShadow: [BoxShadow(color: Colors.black54, blurRadius: 8, offset: Offset(0, 4))],
      ),
      child: SafeArea(
        top: false,
        child: Container(
          padding: EdgeInsets.only(left: 8, right: 8),
          child: Row(
            children: [
              Checkbox(value: selectAll, onChanged: toggleSelectAll),
              const Text('Tất cả'),
              const Spacer(),
              ElevatedButton(
                onPressed: selectedCodes.isNotEmpty ? deleteSelected : null,
                style: ElevatedButton.styleFrom(
                  backgroundColor: BaseColor.primary500,
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                ),
                child: const Text('Xoá', style: TextStyle(fontSize: 14, color: Colors.white)),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
