import 'package:easy_localization/src/public_ext.dart';
import 'package:flutter/material.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/dashboard/menu_entries.dart';
import 'package:mohem_flutter_app/models/get_employee_address_model.dart';
import 'package:mohem_flutter_app/models/get_employee_basic_details.model.dart';
import 'package:mohem_flutter_app/models/get_employee_phones_model.dart';
import 'package:mohem_flutter_app/provider/dashboard_provider_model.dart';
import 'package:mohem_flutter_app/ui/profile/dynamic_screens/dynamic_input_address_screen.dart';
import 'package:mohem_flutter_app/ui/profile/phone_numbers.dart';
import 'package:mohem_flutter_app/widgets/app_bar_widget.dart';
import 'package:provider/provider.dart';

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

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

class _ContactDetailsState extends State<ContactDetails> {
  String? fullName = "";
  String? maritalStatus = "";
  String? birthDate = "";
  String? civilIdentityNumber = "";
  String? emailAddress = "";
  String? employeeNo = "";
  int? correctOrNew = 1;
  List<GetEmployeePhonesList> getEmployeePhonesList = [];
  List<GetEmployeeAddressList> getEmployeeAddressList = [];
  List<GetEmployeeBasicDetailsList> getEmployeeBasicDetailsList = [];
  GetMenuEntriesList menuEntriesPhone = GetMenuEntriesList();
  GetMenuEntriesList menuEntriesAddress = GetMenuEntriesList();

  @override
  void initState() {
    super.initState();
    List<GetMenuEntriesList> menuData = Provider.of<DashboardProviderModel>(context, listen: false).getMenuEntriesList!;

    var filterList = menuData.where((GetMenuEntriesList e) => e.requestType == 'PHONE_NUMBERS').toList();

    if (filterList.isNotEmpty) {
      menuEntriesPhone = filterList.first;
    }
    filterList = menuData.where((GetMenuEntriesList e) => e.requestType == 'ADDRESS').toList();
    if (filterList.isNotEmpty) {
      menuEntriesAddress = filterList.first;
    }

    getEmployeePhones();
  }

  void getEmployeePhones() async {
    try {
      Utils.showLoading(context);
      getEmployeePhonesList = await ProfileApiClient().getEmployeePhones();
      getEmployeeAddressList = await ProfileApiClient().getEmployeeAddress();
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBarWidget(
        context,
        title: LocaleKeys.profile_contactDetails.tr(),
      ),
      backgroundColor: MyColors.backgroundColor,
      // bottomSheet: footer(),
      body: ListView(
        padding: const EdgeInsets.all(21),
        children: [
          if (getEmployeePhonesList.isNotEmpty)
            Stack(
              children: [
                ListView.separated(
                    physics: const NeverScrollableScrollPhysics(),
                    shrinkWrap: true,
                    padding: EdgeInsets.zero,
                    itemBuilder: (cxt, index) => Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            "${getEmployeePhonesList[index].pHONETYPEMEANING}".toText13(color: MyColors.lightGrayColor),
                            ("${getEmployeePhonesList[index].pHONENUMBER}" ?? "").toText16(isBold: true, color: MyColors.blackColor),
                          ],
                        ),
                    separatorBuilder: (cxt, index) => 12.height,
                    itemCount: getEmployeePhonesList.length),
                if (menuEntriesPhone.updateButton == 'Y')
                AppState().isArabic(context)? Positioned(
                    top: 1,
                    left: 1,
                    child: const Icon(Icons.edit_location_alt_outlined, size: 20).onPress(updatePhone),
                  )
                :Positioned(
                  top: 1,
                  right: 1,
                  child: const Icon(Icons.edit_location_alt_outlined, size: 20).onPress(updatePhone),
                ),
              ],
            ).objectContainerView(),
          12.height,
          if (getEmployeeAddressList.isNotEmpty)
            Stack(
              children: [
                ListView.separated(
                    physics: const NeverScrollableScrollPhysics(),
                    shrinkWrap: true,
                    padding: EdgeInsets.zero,
                    itemBuilder: (cxt, index) => Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            "${getEmployeeAddressList[index].sEGMENTPROMPT}".toText13(color: MyColors.lightGrayColor),
                            ("${getEmployeeAddressList[index].sEGMENTVALUEDSP}" ?? "").toText16(isBold: true, color: MyColors.blackColor),
                          ],
                        ),
                    separatorBuilder: (cxt, index) => 12.height,
                    itemCount: getEmployeeAddressList.length),
                if (menuEntriesAddress.updateButton == 'Y')
                  AppState().isArabic(context)? Positioned(
                    top: 1,
                    left: 1,
                    child: const Icon(Icons.edit_location_alt_outlined, size: 20).onPress(addUpdateAddress),
                  )
                      :Positioned(
                    top: 1,
                    right: 1,
                    child: const Icon(Icons.edit_location_alt_outlined, size: 20).onPress(addUpdateAddress),
                  ),
              ],
            ).objectContainerView()
        ],
      ),
    );
  }

  void updatePhone() {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => PhoneNumbers(getEmployeePhonesList: this.getEmployeePhonesList)),
    );
  }

  void addUpdateAddress() {
    Widget cancelButton = TextButton(
      child: Text("Cancel"),
      onPressed: () {
        Navigator.pop(context);
      },
    );
    Widget continueButton = TextButton(
      child: Text("Next"),
      onPressed: () {
        continueDynamicForms();
      },
    );
    StatefulBuilder alert = StatefulBuilder(builder: (context, setState) {
      return AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10.0))),
        title: Text("Confirm"),
        content: Builder(builder: (context) {
          // Get available height and width of the build area of this widget. Make a choice depending on the size.
          var height = MediaQuery.of(context).size.height * .5;
          return Container(
              height: height,
              child: Column(children: [
                Text(
                  "Select the type of change you want to make.",
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                ),
                Divider(),
                Column(
                  children: [
                    ListTile(
                      title: Text("Correct or amend this address"),
                      leading: Radio(
                        value: 1,
                        groupValue: correctOrNew,
                        onChanged: (value) {
                          setState(() {
                            correctOrNew = int.parse(value.toString());
                          });
                        },
                        activeColor: Colors.green,
                      ),
                    ),
                    ListTile(
                      title: Text("Enter a new address if you have moved"),
                      leading: Radio(
                        value: 2,
                        groupValue: correctOrNew,
                        onChanged: (value) {
                          setState(() {
                            correctOrNew = int.parse(value.toString());
                          });
                        },
                        activeColor: Colors.green,
                      ),
                    ),
                  ],
                )
              ]));
        }),
        actions: [
          cancelButton,
          continueButton,
        ],
      );
    });

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }

  void continueDynamicForms() {
    Navigator.pushNamed(context, AppRoutes.addDynamicAddressScreen,
        arguments: DynamicProfileParams(LocaleKeys.profile_address.tr(), 'HR_PERINFO_SS',
            uRL: 'GET_ADDRESS_DFF_STRUCTURE', requestID: 'BASIC_DETAILS', getEmployeeAddressList: getEmployeeAddressList, correctOrNew: correctOrNew!));
  }
}
