import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:iconly/iconly.dart';
import 'package:provider/provider.dart' as pro;
import 'package:responsive_grid/responsive_grid.dart';
import 'package:salespro_admin/Provider/all_expanse_provider.dart';
import 'package:salespro_admin/generated/l10n.dart' as lang;

import '../../const.dart';
import '../../model/income_catehory_model.dart';
import '../Widgets/Constant Data/constant.dart';
import '../Widgets/Constant Data/export_button.dart';
import '../currency/currency_provider.dart';

class PaymentTypesList extends StatefulWidget {
  const PaymentTypesList({Key? key}) : super(key: key);

  // static const String route = '/expenses';

  @override
  State<PaymentTypesList> createState() => _PaymentTypesListState();
}

class _PaymentTypesListState extends State<PaymentTypesList> {
  String searchItem = '';
  TextEditingController paymentTypeNameController = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    checkCurrentUserAndRestartApp();
  }

  final _horizontalScroll = ScrollController();

  showAddorEditPaymentTypeDialog(BuildContext context, List<PaymentTypesModel> allBrands, WidgetRef ref, {String? paymentTypeId}) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text(paymentTypeId == null ? "Add Payment Type" : "Edit Payment Type"),
          content: SizedBox(
            width: 400,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // Add your form fields here
                TextFormField(
                  showCursor: true,
                  cursorColor: kTitleColor,
                  controller: paymentTypeNameController,
                  keyboardType: TextInputType.name,
                  decoration: kInputDecoration.copyWith(
                    contentPadding: const EdgeInsets.all(10.0),
                    //hintText: ('Search by Invoice...'),
                    hintText: "Enter Payment Type Name",
                    suffixIcon: const Icon(
                      FeatherIcons.search,
                      color: kTitleColor,
                    ),
                  ),
                ),
                // Add more fields as needed
              ],
            ),
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text(lang.S.of(context).cancel),
            ),
            ElevatedButton(
              onPressed: () async {
                bool isAlreadyAdded = false;

                final sanitizedInput = sanitizeForFirebaseKey(paymentTypeNameController.text);

                for (final element in allBrands) {
                  if (sanitizeForFirebaseKey(element.paymentTypeName) == sanitizedInput) {
                    isAlreadyAdded = true;
                    EasyLoading.showError(lang.S.of(context).alreadyAdded);
                    break; // Use break instead of return in for-in loop
                  }
                }
                // allBrands.forEach((element) {
                //   if (element.paymentTypeName.toLowerCase().removeAllWhiteSpace() == paymentTypeNameController.text.toLowerCase().removeAllWhiteSpace()) {
                //     isAlreadyAdded = true;
                //     EasyLoading.showError(lang.S.of(context).alreadyAdded);
                //     return;
                //   }
                // });
                final DatabaseReference categoryInformationRef = FirebaseDatabase.instance.ref().child(await getUserID()).child('Payment Types');
                categoryInformationRef.keepSynced(true);
                String pushKeynew = categoryInformationRef.push().key ?? '';
                if (pushKeynew == '') {
                  EasyLoading.showError("An Error Occurred, Please try again later");
                  return;
                }
                if (paymentTypeId != null) {
                  //Get the key from rtdb
                  isAlreadyAdded
                      ? EasyLoading.showError(lang.S.of(context).alreadyAdded)
                      : categoryInformationRef.update(
                          {paymentTypeId: PaymentTypesModel(id: paymentTypeId, paymentTypeName: paymentTypeNameController.text.trim()).toJson()},
                        );
                } else {
                  PaymentTypesModel brandModel = PaymentTypesModel(
                    id: pushKeynew,
                    paymentTypeName: paymentTypeNameController.text.trim(),
                  );
                  isAlreadyAdded ? EasyLoading.showError(lang.S.of(context).alreadyAdded) : categoryInformationRef.child(pushKeynew).set(brandModel.toJson());
                }
                ref.refresh(paymentTypeProvider);
                isAlreadyAdded ? null : ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("${paymentTypeId == null ? 'Added' : 'Updated'} Successfully")));

                // ignore: use_build_context_synchronously
                isAlreadyAdded ? null : Navigator.pop(context);
              },
              child: paymentTypeId == null ? Text(lang.S.of(context).save) : Text(lang.S.of(context).update),
            ),
          ],
        );
      },
    );
  }

  String sanitizeForFirebaseKey(String input) {
    return input
        .replaceAll(RegExp(r'[.#$\[\]]'), '') // remove invalid characters
        .replaceAll(' ', '') // remove whitespaces
        .toLowerCase(); // make it lowercase (optional)
  }

  @override
  Widget build(BuildContext context) {
    final currencyProvider = pro.Provider.of<CurrencyProvider>(context);
    final globalCurrency = currencyProvider.currency ?? '\$';
    final theme = Theme.of(context);
    final screenWidth = MediaQuery.of(context).size.width;
    return SafeArea(
      child: Consumer(
        builder: (context, ref, child) {
          final expenses = ref.watch(paymentTypeProvider);
          return expenses.when(data: (showExpense) {
            //Filter the expenses based on the search term
            showExpense = showExpense.where((expense) {
              return expense.paymentTypeName.toLowerCase().contains(searchItem.toLowerCase());
            }).toList();
            return Scaffold(
                backgroundColor: kDarkWhite,
                body: SingleChildScrollView(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const SizedBox(height: 20),
                      Container(
                        // padding: const EdgeInsets.only(left: 20.0, right: 20.0, top: 10.0, bottom: 10.0),
                        decoration: BoxDecoration(borderRadius: BorderRadius.circular(20.0), color: kWhite),
                        child: Column(
                          children: [
                            const SizedBox(height: 10),
                            Padding(
                              padding: const EdgeInsets.symmetric(horizontal: 16),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Flexible(
                                    child: Text(
                                      "Payment Types",
                                      maxLines: 2,
                                      overflow: TextOverflow.ellipsis,
                                      style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w700),
                                    ),
                                  ),
                                  ElevatedButton.icon(
                                    style: ElevatedButton.styleFrom(),
                                    onPressed: () async {
                                      if (await checkUserRolePermission(type: "payment-type-create")) {
                                        paymentTypeNameController.clear();
                                        showAddorEditPaymentTypeDialog(context, showExpense, ref);
                                      }
                                    },
                                    icon: const Icon(
                                      Icons.add,
                                      color: Colors.white,
                                    ),
                                    label: Text(
                                      "Add Payment Type",
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            const SizedBox(height: 10),
                            const Divider(
                              height: 1,
                              thickness: 1.0,
                              color: kDividerColor,
                            ),
                            const SizedBox(height: 10),

                            ///___________search________________________________________________-
                            ResponsiveGridRow(rowSegments: 100, children: [
                              ResponsiveGridCol(
                                xs: 100,
                                md: 60,
                                lg: 35,
                                child: Padding(
                                  padding: const EdgeInsets.all(10),
                                  child: TextFormField(
                                    showCursor: true,
                                    cursorColor: kTitleColor,
                                    onChanged: (value) {
                                      setState(() {
                                        searchItem = value;
                                      });
                                    },
                                    keyboardType: TextInputType.name,
                                    decoration: kInputDecoration.copyWith(
                                      contentPadding: const EdgeInsets.all(10.0),
                                      //hintText: ('Search by Invoice...'),
                                      hintText: ('Search by Payment Type...'),
                                      suffixIcon: const Icon(
                                        FeatherIcons.search,
                                        color: kTitleColor,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ]),

                            ///__________expense_LIst____________________________________________________________________

                            const SizedBox(height: 10.0),
                            showExpense.isNotEmpty
                                ? Column(
                                    children: [
                                      LayoutBuilder(
                                        builder: (context, constrains) {
                                          return Scrollbar(
                                            controller: _horizontalScroll,
                                            thumbVisibility: true,
                                            radius: const Radius.circular(8),
                                            thickness: 8,
                                            child: SingleChildScrollView(
                                              scrollDirection: Axis.horizontal,
                                              controller: _horizontalScroll,
                                              child: ConstrainedBox(
                                                constraints: BoxConstraints(
                                                  minWidth: constrains.maxWidth,
                                                  minHeight: MediaQuery.of(context).size.height - 260,
                                                ),
                                                child: Theme(
                                                  data: ThemeData(
                                                    dividerColor: kNeutral300,
                                                    textTheme: theme.textTheme,
                                                  ),
                                                  child: DataTable(
                                                      border: const TableBorder(
                                                        horizontalInside: BorderSide(
                                                          width: 1,
                                                          color: kNeutral300,
                                                        ),
                                                      ),
                                                      dataRowColor: const WidgetStatePropertyAll(Colors.white),
                                                      headingRowColor: WidgetStateProperty.all(const Color(0xFFF8F3FF)),
                                                      showBottomBorder: true,
                                                      dividerThickness: 1.0,
                                                      headingTextStyle: theme.textTheme.titleMedium,
                                                      columns: [
                                                        DataColumn(label: Text(lang.S.of(context).SL)),
                                                        DataColumn(label: Text(lang.S.of(context).date)),
                                                        DataColumn(headingRowAlignment: MainAxisAlignment.center, label: Text(lang.S.of(context).setting)),
                                                      ],
                                                      rows: List.generate(showExpense.length, (index) {
                                                        return DataRow(cells: [
                                                          ///______________S.L__________________________________________________
                                                          DataCell(
                                                            Text('${index + 1}'),
                                                          ),

                                                          ///______________Date__________________________________________________
                                                          DataCell(
                                                            Text(
                                                              showExpense[index].paymentTypeName,
                                                            ),
                                                          ),

                                                          ///_______________actions_________________________________________________
                                                          DataCell(
                                                            Center(
                                                              child: SizedBox(
                                                                width: 25,
                                                                child: Theme(
                                                                  data: ThemeData(highlightColor: dropdownItemColor, focusColor: dropdownItemColor, hoverColor: dropdownItemColor),
                                                                  child: PopupMenuButton(
                                                                    surfaceTintColor: Colors.white,
                                                                    padding: EdgeInsets.zero,
                                                                    itemBuilder: (BuildContext bc) => [
                                                                      ///____________edit___________________________________________
                                                                      PopupMenuItem(
                                                                        onTap: () async {
                                                                          if (await checkUserRolePermission(type: "payment-type-update")) {
                                                                            paymentTypeNameController.text = showExpense[index].paymentTypeName;
                                                                            showAddorEditPaymentTypeDialog(context, showExpense, ref, paymentTypeId: showExpense[index].id);
                                                                          }
                                                                        },
                                                                        child: Row(
                                                                          children: [
                                                                            Icon(IconlyLight.edit, size: 22.0, color: kGreyTextColor),
                                                                            const SizedBox(width: 4.0),
                                                                            Text(
                                                                              lang.S.of(context).edit,
                                                                              style: theme.textTheme.bodyLarge?.copyWith(
                                                                                color: kGreyTextColor,
                                                                              ),
                                                                            ),
                                                                          ],
                                                                        ),
                                                                      ),

                                                                      ///____________delete___________________________________________
                                                                      PopupMenuItem(
                                                                        onTap: () async {
                                                                          if (await checkUserRolePermission(type: "payment-type-delete")) {
                                                                            final DatabaseReference categoryInformationRef =
                                                                                FirebaseDatabase.instance.ref().child(await getUserID()).child('Payment Types');
                                                                            categoryInformationRef.keepSynced(true);
                                                                            categoryInformationRef.child(showExpense[index].id).remove();
                                                                            ref.refresh(paymentTypeProvider);
                                                                            ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("Deleted Successfully")));
                                                                          }
                                                                        },
                                                                        child: Row(
                                                                          children: [
                                                                            Icon(IconlyLight.delete, size: 22.0, color: kGreyTextColor),
                                                                            const SizedBox(width: 4.0),
                                                                            Text(
                                                                              lang.S.of(context).delete,
                                                                              style: theme.textTheme.bodyLarge?.copyWith(
                                                                                color: kGreyTextColor,
                                                                              ),
                                                                            ),
                                                                          ],
                                                                        ),
                                                                      ),
                                                                    ],
                                                                    child: Center(
                                                                      child: Container(
                                                                          height: 18,
                                                                          width: 18,
                                                                          alignment: Alignment.centerRight,
                                                                          child: const Icon(
                                                                            Icons.more_vert,
                                                                            size: 18,
                                                                          )),
                                                                    ),
                                                                  ),
                                                                ),
                                                              ),
                                                            ),
                                                          ),
                                                        ]);
                                                      })),
                                                ),
                                              ),
                                            ),
                                          );
                                        },
                                      ),
                                    ],
                                  )
                                //: const EmptyWidget(title: 'No Expense Found'),
                                : EmptyWidget(title: "No Payment Type Found"),
                          ],
                        ),
                      ),
                      // Visibility(visible: MediaQuery.of(context).size.height != 0, child: const Footer()),
                    ],
                  ),
                ));
            // return ExpensesTableWidget(expenses: allExpenses);
          }, error: (e, stack) {
            print(stack);
            return Center(
              child: Text(e.toString()),
            );
          }, loading: () {
            return const Center(
              child: CircularProgressIndicator(),
            );
          });
        },
      ),
    );
  }
}
