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:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:mobile_pos/Provider/category,brans,units_provide.dart';
// import 'package:mobile_pos/Provider/all_expanse_provider.dart';
import 'package:mobile_pos/generated/l10n.dart' as lang;
import 'package:mobile_pos/model/income_model.dart';
import 'package:nb_utils/nb_utils.dart';

import '../../GlobalComponents/button_global.dart';
import '../../Provider/all_expanse_provider.dart';
import '../../const_commas.dart';
import '../../constant.dart';
import '../../currency.dart';
import '../../model/DailyTransactionModel.dart';
import 'income_category_list.dart';

// ignore: must_be_immutable
class AddIncome extends StatefulWidget {
  const AddIncome({
    super.key,
  });

  @override
  // ignore: library_private_types_in_public_api
  _AddIncomeState createState() => _AddIncomeState();
}

class _AddIncomeState extends State<AddIncome> {
  // String dropdownValue = lang.S.current.selectCategory;
  String dropdownValue = "Select Category";
  final dateController = TextEditingController();
  TextEditingController incomeForNameController = TextEditingController();
  final TextEditingController incomeAmountController = TextEditingController();
  TextEditingController incomeNoteController = TextEditingController();
  TextEditingController incomeRefController = TextEditingController();

  // List<String> get paymentMethods => [
  //       // lang.S.current.cash,
  //       'Cash',
  //       // lang.S.current.bank,
  //       'Bank',
  //       // lang.S.current.card,
  //       'Card',
  //       // lang.S.current.mobilePayment,
  //       'Mobile Payment',
  //       // lang.S.current.Snacks,
  //       'Snacks',
  //     ];

  DateTime selectedDate = DateTime.now();
  String amountText = '';

  Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
        context: context,
        initialDate: selectedDate,
        firstDate: DateTime(2015, 8),
        lastDate: DateTime(2101));
    if (picked != null && picked != selectedDate) {
      setState(() {
        selectedDate = picked;
      });
    }
  }

  String? selectedPaymentType;

  GlobalKey<FormState> formKey = GlobalKey<FormState>();

  bool validateAndSave() {
    final form = formKey.currentState;
    if (form!.validate()) {
      form.save();
      return true;
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return Consumer(builder: (context, ref, __) {
      final paymentData = ref.watch(paymentTypeProvider);
      return Scaffold(
        backgroundColor: kMainColor,
        appBar: AppBar(
          backgroundColor: kMainColor,
          title: Text(
            'Add Income',
            style: GoogleFonts.poppins(
              color: Colors.white,
            ),
          ),
          centerTitle: true,
          iconTheme: const IconThemeData(color: Colors.white),
          elevation: 0.0,
        ),
        body: Container(
          alignment: Alignment.topCenter,
          decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius:
                  BorderRadius.only(topRight: Radius.circular(30), topLeft: Radius.circular(30))),
          child: SingleChildScrollView(
            child: SizedBox(
              width: context.width(),
              child: Padding(
                padding: const EdgeInsets.all(20.0),
                child: Form(
                    key: formKey,
                    child: Column(
                      children: [
                        ///_______date________________________________
                        FormField(
                          builder: (FormFieldState<dynamic> field) {
                            return InputDecorator(
                              decoration: InputDecoration(
                                suffixIcon:
                                    const Icon(FeatherIcons.calendar, color: kGreyTextColor),
                                enabledBorder: const OutlineInputBorder(),
                                contentPadding: const EdgeInsets.all(20),
                                labelText: 'Income Date',
                                hintText: 'Enter Income Date',
                              ),
                              child: Text(
                                '${DateFormat.d().format(selectedDate)} ${DateFormat.MMM().format(selectedDate)} ${DateFormat.y().format(selectedDate)}',
                              ),
                            );
                          },
                        ).onTap(() => _selectDate(context)),
                        const SizedBox(height: 20),

                        ///_________category_______________________________________________
                        Container(
                          height: 60.0,
                          width: MediaQuery.of(context).size.width,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(5.0),
                            border: Border.all(color: kGreyTextColor),
                          ),
                          child: GestureDetector(
                            onTap: () async {
                              dropdownValue = await const IncomeCategoryList().launch(context);
                              setState(() {});
                            },
                            child: Row(
                              children: [
                                const SizedBox(
                                  width: 10.0,
                                ),
                                Text(
                                  dropdownValue,
                                  style: TextStyle(fontSize: 16),
                                ),
                                const Spacer(),
                                const Icon(Icons.keyboard_arrow_down),
                                const SizedBox(
                                  width: 10.0,
                                ),
                              ],
                            ),
                          ),
                        ),
                        const SizedBox(height: 20),

                        ///________Income_for_______________________________________________
                        TextFormField(
                          showCursor: true,
                          controller: incomeForNameController,
                          validator: (value) {
                            if (value.isEmptyOrNull) {
                              //return 'Please Enter Name';
                              return lang.S.of(context).pleaseEnterName;
                            }
                            return null;
                          },
                          onSaved: (value) {
                            incomeForNameController.text = value!;
                          },
                          decoration: InputDecoration(
                            border: const OutlineInputBorder(),
                            labelText: 'Income For',
                            // hintText: 'Enter Name',
                            hintText: 'Enter Income Name',
                          ),
                        ),
                        const SizedBox(height: 20),

                        ///________PaymentType__________________________________
                        paymentData.when(
                            data: (payment) {
                              return DropdownButtonFormField(
                                  decoration: InputDecoration(
                                    labelText: lang.S.of(context).paymentType,
                                    hintText: 'Select Payment Type',
                                    border: const OutlineInputBorder(),
                                  ),
                                  initialValue: selectedPaymentType,
                                  items: payment.map((entry) {
                                    return DropdownMenuItem(
                                        value: entry.paymentTypeName,
                                        child: Text(entry.paymentTypeName));
                                  }).toList(),
                                  onChanged: (value) {
                                    setState(() {
                                      selectedPaymentType = value.toString();
                                    });
                                  });
                            },
                            error: (e, stack) => Center(
                                  child: Text(e.toString()),
                                ),
                            loading: () => Center(
                                  child: CircularProgressIndicator(),
                                )),
                        const SizedBox(height: 20),

                        ///_________________Amount_____________________________
                        TextFormField(
                          showCursor: true,
                          controller: incomeAmountController,
                          onChanged: (value) {
                            amountText = value.replaceAll(',', '');
                            var formattedText = myFormat.format(int.parse(amountText));
                            incomeAmountController.value = incomeAmountController.value.copyWith(
                              text: formattedText,
                              selection: TextSelection.collapsed(offset: formattedText.length),
                            );
                          },
                          validator: (value) {
                            if (amountText.isEmptyOrNull) {
                              // return 'please Inter Amount';
                              return lang.S.of(context).pleaseInterAmount;
                            } else if (double.tryParse(amountText) == null) {
                              //  return 'Enter a valid Amount';
                              return lang.S.of(context).enterAValidAmount;
                            }
                            return null;
                          },
                          // onSaved: (value) {
                          //   amountText = value!;
                          // },
                          decoration: InputDecoration(
                            border: const OutlineInputBorder(),
                            errorBorder: const OutlineInputBorder(
                                borderSide: BorderSide(color: Colors.red)),
                            labelText: lang.S.of(context).amount,
                            //hintText: 'Enter Amount',
                            hintText: lang.S.of(context).enterAmount,
                          ),
                          keyboardType: TextInputType.number,
                        ),

                        const SizedBox(height: 20),

                        ///_______reference_________________________________
                        TextFormField(
                          showCursor: true,
                          controller: incomeRefController,
                          validator: (value) {
                            return null;
                          },
                          onSaved: (value) {
                            incomeRefController.text = value!;
                          },
                          decoration: InputDecoration(
                            border: const OutlineInputBorder(),
                            labelText: lang.S.of(context).referenceNumber,
                            hintText: lang.S.of(context).enterReferenceNumber,
                          ),
                        ),
                        const SizedBox(height: 20),

                        ///_________note____________________________________________________
                        TextFormField(
                          showCursor: true,
                          controller: incomeNoteController,
                          validator: (value) {
                            if (value == null) {
                              //return 'please Inter Amount';
                              return lang.S.of(context).pleaseInterAmount;
                            }
                            return null;
                          },
                          onSaved: (value) {
                            incomeNoteController.text = value!;
                          },
                          decoration: InputDecoration(
                            border: const OutlineInputBorder(),
                            labelText: lang.S.of(context).note,
                            // hintText: 'Enter Note',
                            hintText: lang.S.of(context).enterNote,
                          ),
                        ),
                        const SizedBox(height: 20),

                        ///_______button_________________________________
                        ButtonGlobal(
                          // buttontext: 'Continue',
                          buttontext: lang.S.of(context).ContinueE,
                          buttonDecoration: kButtonDecoration.copyWith(color: kMainColor),
                          onPressed: () async {
                            if (dropdownValue != 'Select Category') {
                              if (validateAndSave()) {
                                IncomeModel income = IncomeModel(
                                  incomeDate: selectedDate.toString(),
                                  category: dropdownValue,
                                  account: '',
                                  amount: amountText,
                                  incomeFor: incomeForNameController.text,
                                  paymentType: selectedPaymentType.toString(),
                                  referenceNo: incomeRefController.text,
                                  note: incomeNoteController.text,
                                );

                                try {
                                  EasyLoading.show(
                                      status: '${lang.S.of(context).loading}...',
                                      dismissOnTap: false);
                                  final DatabaseReference incomeRef = FirebaseDatabase.instance
                                      .ref()
                                      .child(constUserId)
                                      .child('Income');
                                  incomeRef.keepSynced(true);
                                  incomeRef.push().set(income.toJson());
                                  incomeRef.onChildAdded.listen((event) {
                                    ref.refresh(incomeProvider);
                                  });

                                  ///________daily_transactionModel_________________________________________________________________________

                                  DailyTransactionModel dailyTransaction = DailyTransactionModel(
                                    name: income.incomeFor,
                                    date: income.incomeDate,
                                    type: 'Income',
                                    total: income.amount.toDouble(),
                                    paymentIn: 0,
                                    paymentOut: income.amount.toDouble(),
                                    remainingBalance: income.amount.toDouble(),
                                    id: income.incomeDate,
                                    incomeModel: income,
                                  );
                                  await postDailyTransaction(
                                      dailyTransactionModel: dailyTransaction);

                                  ///____provider_refresh____________________________________________

                                  EasyLoading.showSuccess(lang.S.of(context).addedSuccessfully,
                                      duration: const Duration(milliseconds: 500));
                                  Navigator.pop(context);
                                } catch (e) {
                                  EasyLoading.dismiss();
                                  ScaffoldMessenger.of(context)
                                      .showSnackBar(SnackBar(content: Text(e.toString())));
                                }
                              }
                            } else {
                              //EasyLoading.showError('Please select a category first');
                              EasyLoading.showError(lang.S.of(context).pleaseSelectACategoryFirst);
                            }
                          },
                          iconWidget: Icons.arrow_forward,
                          iconColor: Colors.white,
                        ),
                      ],
                    )),
              ),
            ),
          ),
        ),
      );
    });
  }
}
