import 'package:easy_localization/src/public_ext.dart';
import 'package:flutter/material.dart';
import 'package:mohem_flutter_app/api/leave_balance_api_client.dart';
import 'package:mohem_flutter_app/api/profile_api_client.dart';
import 'package:mohem_flutter_app/app_state/app_state.dart';
import 'package:mohem_flutter_app/classes/colors.dart';
import 'package:mohem_flutter_app/classes/utils.dart';
import 'package:mohem_flutter_app/config/routes.dart';
import 'package:mohem_flutter_app/extensions/int_extensions.dart';
import 'package:mohem_flutter_app/extensions/string_extensions.dart';
import 'package:mohem_flutter_app/extensions/widget_extensions.dart';
import 'package:mohem_flutter_app/generated/locale_keys.g.dart';
import 'package:mohem_flutter_app/models/get_employee_phones_model.dart';
import 'package:mohem_flutter_app/models/profile/phone_number_types_model.dart';
import 'package:mohem_flutter_app/models/profile/submit_phone_transactions.dart';
import 'package:mohem_flutter_app/ui/misc/request_submit_screen.dart';
import 'package:mohem_flutter_app/widgets/app_bar_widget.dart';
import 'package:mohem_flutter_app/widgets/button/default_button.dart';
import 'package:mohem_flutter_app/widgets/dynamic_forms/dynamic_textfield_widget.dart';

class PhoneNumbers extends StatefulWidget {
  List<GetEmployeePhonesList> getEmployeePhonesList;

  PhoneNumbers({Key? key, required this.getEmployeePhonesList}) : super(key: key);

  @override
  _PhoneNumbersState createState() => _PhoneNumbersState();
}

class _PhoneNumbersState extends State<PhoneNumbers> {
  List<GetPhoneNumberTypesModel> getPhoneNumberTypesList = [];
  SubmitPhonesTransactionList submitPhoneNumbers = SubmitPhonesTransactionList();

  @override
  void initState() {
    super.initState();
    getPhoneNumberTypes();
  }

  void getPhoneNumberTypes() async {
    Utils.showLoading(context);
    getPhoneNumberTypesList = await ProfileApiClient().getPhoneNumberTypes();
    setState(() {});
    Utils.hideLoading(context);
  }

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBarWidget(
        context,
        title: LocaleKeys.profile_contactDetails.tr(),
      ),
      backgroundColor: MyColors.backgroundColor,
      body: Column(
        children: [
          ListView(
            physics: const BouncingScrollPhysics(),
            padding: const EdgeInsets.all(21),
            children: [
              DefaultButton("+ ${LocaleKeys.addRow.tr()}", () {
                widget.getEmployeePhonesList.add(GetEmployeePhonesList(aCTION: 'NEW_ROW'));
                setState(() {});
              }),
              12.height,
              ListView.separated(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  itemBuilder: (cxt, index) {
                    var element = widget.getEmployeePhonesList[index];
                    return element.aCTION != 'DELETE_ROW'
                        ? Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                            PopupMenuButton(
                                child: DynamicTextFieldWidget(
                                  LocaleKeys.selectTypeT.tr(),
                                  element.pHONETYPEMEANING ?? LocaleKeys.pleaseSelect.tr(),
                                  isEnable: false,
                                  isPopup: true,
                                ).paddingOnly(bottom: 12),
                                itemBuilder: (_) => <PopupMenuItem<int>>[
                                      for (int i = 0; i < getPhoneNumberTypesList.length; i++) PopupMenuItem<int>(child: Text(getPhoneNumberTypesList![i].mEANING!), value: i),
                                    ],
                                onSelected: (int index) {
                                  element.pHONETYPEMEANING = getPhoneNumberTypesList[index].mEANING;
                                  element.pHONETYPE = getPhoneNumberTypesList[index].cODE;
                                  setState(() {});
                                }),
                            DynamicTextFieldWidget(
                              "Value",
                              element.pHONENUMBER ?? "",
                              isReadOnly: false,
                              onChange: (text) {
                                element.pHONENUMBER = text;
                              },
                            ).paddingOnly(bottom: 12),
                            Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                              Icon(Icons.delete, color: MyColors.redColor, size: 18),
                              LocaleKeys.delete.tr().toText14(color: MyColors.redColor),
                            ]).onPress(() {
                              element.aCTION = 'DELETE_ROW';
                              setState(() {});
                            }),
                          ]).objectContainerView().paddingOnly(bottom: 12)
                        : Container();
                  },
                  separatorBuilder: (cxt, index) => 0.height,
                  itemCount: widget.getEmployeePhonesList.length)
            ],
          ).expanded,
          DefaultButton(LocaleKeys.update.tr(), () async {
            updatePhone();
          }).insideContainer
        ],
      ),
    );
  }

  void updatePhone() async {
    Utils.showLoading(context);
    setUpdateStatus();
    submitPhoneNumbers = await ProfileApiClient().submitPhoneNumbers(widget.getEmployeePhonesList);
    Utils.hideLoading(context);
    await Navigator.pushNamed(context, AppRoutes.requestSubmitScreen,
        arguments: RequestSubmitScreenParams(LocaleKeys.profile_contactDetails.tr(), submitPhoneNumbers.pTRANSACTIONID!, submitPhoneNumbers.pITEMKEY!, 'phone_numbers'));
    if (!AppState().cancelRequestTrancsection) {
      return;
    }
    Utils.showLoading(context);
    await LeaveBalanceApiClient().cancelHrTransaction(submitPhoneNumbers.pTRANSACTIONID!);
    Utils.hideLoading(context);
  }

  void setUpdateStatus() {
    widget.getEmployeePhonesList.forEach((element) {
      if (element.aCTION == null) {
        element.aCTION = 'UPDATE_ROW';
        element.dATEFROM = '';
        element.dATETO = '';
      }
    });
  }
}
