import 'package:flutter/material.dart';
import 'package:get/get.dart';


import '../../../core/utils/SessionCache.dart';
import '../../../core/utils/app_utils.dart';
import '../../../custom_widgets/custom_app_bar.dart';
import '../../../custom_widgets/custom_dialog.dart';
import '../../../custom_widgets/custom_no_record.dart';
import '../../../res/app_colors.dart';
import '../../../routes/app_pages.dart';
import '../controllers/beneficiary_management_controller.dart';

class BeneficiaryManagementView extends GetView<BeneficiaryManagementController> {
  const BeneficiaryManagementView({Key? key, this.showAppBar = true}) : super(key: key);
  final bool showAppBar;

  @override
  Widget build(BuildContext context) {
    String className = runtimeType.toString().split('.').last;
    controller.className = className;
    return Scaffold(
      appBar: showAppBar
          ? DashBoardAppBar(
              title: "Beneficiary Management",
              onBackButtonPressed: () {
                Get.back(result: controller.hasUpdated.value);
              },
            )
          : null,
      floatingActionButton: InkWell(
        onTap: () async {
          var result = await Get.toNamed(Routes.NEW_BENEFICIARY);
          if (result != null && result == true) {
            controller.fetchBeneficiaries();
            controller.hasUpdated.value = true;
          }
        },
        child: Container(
          height: 30,
          width: 130,
          decoration: const BoxDecoration(color: AppColors.colorButton, borderRadius: BorderRadius.all(Radius.circular(20.0))),
          child: const Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [Icon(Icons.add, size: 14, color: AppColors.white), SizedBox(width: 5), Text("Add Beneficiary", style: TextStyle(color: AppColors.white, fontWeight: FontWeight.w500, fontSize: 12))],
          ),
        ),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 20.0),
              child: TextField(
                  style: Theme.of(context).textTheme.bodySmall?.copyWith(fontWeight: FontWeight.w400, fontSize: 12),
                  decoration: const InputDecoration(
                    suffixIconColor: AppColors.colorPrimary,
                    filled: true,
                    fillColor: AppColors.colorGrey200,
                    enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(10.0)), borderSide: BorderSide(width: 1, color: Colors.transparent)),
                    border: OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(10.0)), borderSide: BorderSide(width: 1, color: AppColors.colorGrey500)),
                    focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(10.0)), borderSide: BorderSide(width: 1, style: BorderStyle.solid, color: Colors.transparent)),
                    hintText: 'Search By Beneficiary Name',
                    hintStyle: TextStyle(fontSize: 12, fontWeight: FontWeight.w400, color: AppColors.colorGrey500),
                    suffixIcon: Icon(Icons.search_rounded),
                  ),
                  onChanged: (value) {
                    controller.filterBeneficiaries(value);
                  }),
            ),
            Container(
              height: 40,
              width: double.infinity,
              color: AppColors.FDF7F1,
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 25.0, vertical: 10.0),
                child: Text("Bank Transfer", style: Theme.of(context).textTheme.titleSmall?.copyWith(color: AppColors.black, fontWeight: FontWeight.w400, fontSize: 13)),
              ),
            ),
            const SizedBox(height: 20.0),
            Obx(() {
              if (controller.filteredBeneficiaries.isEmpty) {
                return const Center(
                  child: CustomNoRecord(title: "No Record Found", description: "We couldn't find any activity at this moment"),
                );
              } else {
                return ListView.separated(
                  shrinkWrap: true,
                  // physics: const NeverScrollableScrollPhysics(),
                  itemBuilder: (context, index) {
                    final beneficiary = controller.filteredBeneficiaries[index];
                    return Column(
                      children: [
                        Container(
                          width: double.infinity,
                          padding: const EdgeInsets.all(15.0),
                          decoration: const BoxDecoration(
                            color: AppColors.white,
                            borderRadius: BorderRadius.all(Radius.circular(8.0)),
                          ),
                          child: Row(
                            children: [
                              CircleAvatar(radius: 20.0, backgroundColor: AppColors.colorGrey300, child: Text(AppUtils.getInitials(beneficiary.mbmBkmstitleRef), style: Theme.of(context).textTheme.titleSmall)),
                              const SizedBox(width: 10),
                              Expanded(
                                flex: 4,
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(beneficiary.refNickName, style: Theme.of(context).textTheme.titleMedium?.copyWith(color: AppColors.colorGrey700, fontWeight: FontWeight.w500, fontSize: 14)),
                                    const SizedBox(height: 5),
                                    Text(beneficiary.mbmBkmstitleRef, style: Theme.of(context).textTheme.titleMedium?.copyWith(color: AppColors.colorGrey600, fontWeight: FontWeight.w400, fontSize: 12)),
                                    const SizedBox(height: 5),
                                    Text(beneficiary.mbmBkmsnumberRef, style: Theme.of(context).textTheme.titleMedium?.copyWith(color: AppColors.colorPrimary, fontWeight: FontWeight.w400, fontSize: 12)),
                                  ],
                                ),
                              ),
                              Expanded(
                                flex: 1,
                                child: Align(
                                  alignment: Alignment.centerRight,
                                  child: PopupMenuButton<int>(
                                    padding: const EdgeInsets.all(0.0),
                                    offset: const Offset(-25, 30),
                                    color: AppColors.white,
                                    icon: const Icon(Icons.more_vert_rounded, color: AppColors.colorGrey500),
                                    onSelected: (value) {},
                                    itemBuilder: (context) => [
                                      _buildPopupMenuItem(context, "Pay", 0, () {
                                        Get.toNamed(Routes.BENEFICIARY_TRANSFER_MONEY, arguments: [beneficiary]);
                                      }),
                                      _buildPopupMenuItem(context, "Delete", 1, () {
                                        CustomDialog.showAlertDialog(
                                            onTapPositive: () {
                                              Navigator.of(context, rootNavigator: true).pop();
                                              controller.deleteSingleBeneficiary(beneficiary.mbmBkmsnumberRef, SessionCache.instance.userInfo.cmpUserId, SessionCache.instance.userInfo.porOrgacode);
                                            },
                                            onTapNegative: () {
                                              Navigator.of(context, rootNavigator: true).pop();
                                            },
                                            context: context);
                                      }),
                                    ],
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    );
                  },
                  separatorBuilder: (BuildContext context, int index) {
                    return Container(height: 1, color: AppColors.black.withOpacity(0.2));
                  },
                  itemCount: controller.filteredBeneficiaries.length,
                );
              }
            }),
          ],
        ),
      ),
    );
  }

  /// For List Actions
  PopupMenuItem<int> _buildPopupMenuItem(BuildContext context, String text, int value, Function() onTap) {
    return PopupMenuItem<int>(
      height: 10,
      onTap: onTap,
      value: value,
      padding: const EdgeInsets.symmetric(vertical: 5.0),
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 0.0, horizontal: 8.0),
        child: Text(text, style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w500)),
      ),
    );
  }
}
