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_basic_details.model.dart';
import 'package:mohem_flutter_app/models/member_information_list_model.dart';
import 'package:mohem_flutter_app/provider/dashboard_provider_model.dart';
import 'package:mohem_flutter_app/ui/profile/dynamic_screens/dynamic_input_basic_details_screen.dart';
import 'package:mohem_flutter_app/widgets/app_bar_widget.dart';
import 'package:mohem_flutter_app/widgets/button/default_button.dart';
import 'package:provider/provider.dart';

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

  @override
  _BasicDetailsState createState() => _BasicDetailsState();
}
// TODO(Sultan): kindly follow structure of code written. use extension methods for widgets, use localization and format code

class _BasicDetailsState extends State<BasicDetails> {
  String? fullName = "";
  String? maritalStatus = "";
  String? birthDate = "";
  String? civilIdentityNumber = "";
  String? emailAddress = "";
  String? employeeNo = "";
  int correctOrNew = 1;
  List<GetEmployeeBasicDetailsList>? getEmployeeBasicDetailsList;

  late MemberInformationListModel memberInformationList;
  GetMenuEntriesList menuEntries = GetMenuEntriesList();

  @override
  void initState() {
    super.initState();
    memberInformationList = AppState().memberInformationList!;
    List<GetMenuEntriesList> menuData = Provider.of<DashboardProviderModel>(context, listen: false).getMenuEntriesList!;
    for (int i = 0; i < menuData.length; i++) {
      menuData[i].icon == "";
    }

    var filterList = menuData.where((e) => e.requestType == 'BASIC_DETAILS').toList();
    if (filterList.isNotEmpty) {
      menuEntries = filterList.first;
    }

    getEmployeeBasicDetails();
  }

  void getEmployeeBasicDetails() async {
    try {
      Utils.showLoading(context);
      getEmployeeBasicDetailsList = await ProfileApiClient().getEmployeeBasicDetails();
      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_basicDetails.tr(),
        ),
        backgroundColor: MyColors.backgroundColor,
        body: Column(
          children: [
            Expanded(
              child: ListView(
                padding: const EdgeInsets.all(21),
                children: [
                  getEmployeeBasicDetailsList == null
                      ? const SizedBox()
                      : (getEmployeeBasicDetailsList!.isEmpty
                          ? Utils.getNoDataWidget(context)
                          : Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: getEmployeeBasicDetailsList!
                                      .map((e) => Column(
                                            children: [
                                              e.dISPLAYFLAG == "Y"
                                                  ? Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                                                      "${e.sEGMENTPROMPT}".toText13(color: MyColors.lightGrayColor),
                                                      "${e.sEGMENTVALUEDSP}".toText16(isBold: true, color: MyColors.blackColor),
                                                      12.height
                                                    ])
                                                  : Container(),
                                            ],
                                          ))
                                      .toList())
                              .objectContainerView())
                ],
              ),
            ),
            DefaultButton(
                    LocaleKeys.update.tr(),
                    menuEntries.updateButton == 'Y'
                        ? () async {
                            showAlertDialog(context);
                          }
                        : null)
                .insideContainer,
          ],
        ));
  }

  void showAlertDialog(BuildContext context) {
    Widget cancelButton = TextButton(
      child: Text(LocaleKeys.cancel.tr()),
      onPressed: () {
        Navigator.pop(context);
      },
    );
    Widget continueButton = TextButton(
      child: Text(LocaleKeys.next.tr()),
      onPressed: () {
        continueDynamicForms();
      },
    );
    StatefulBuilder alert = StatefulBuilder(builder: (context, setState) {
      return AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10.0))),
        title: Text(LocaleKeys.confirm.tr()),
        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(
                  LocaleKeys.selectType.tr(),
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                ),
                Divider(),
                Column(
                  children: [
                    ListTile(
                      title: Text(LocaleKeys.correctCurrentDatails.tr()),
                      leading: Radio(
                        value: 1,
                        groupValue: correctOrNew,
                        onChanged: (value) {
                          setState(() {
                            correctOrNew = int.parse(value.toString());
                          });
                        },
                        activeColor: Colors.green,
                      ),
                    ),
                    ListTile(
                      title: Text(LocaleKeys.enterNewInfo.tr()),
                      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.addDynamicInputProfile,
        arguments: DynamicProfileParams(LocaleKeys.profile_basicDetails.tr(), 'HR_PERINFO_SS',
            uRL: 'GET_BASIC_DET_DFF_STRUCTURE', requestID: 'BASIC_DETAILS', getEmployeeBasicDetailsList: getEmployeeBasicDetailsList, correctOrNew: correctOrNew));
  }
}
