import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:mohem_flutter_app/api/profile_api_client.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/dyanmic_forms/validate_eit_transaction_model.dart';
import 'package:mohem_flutter_app/models/get_approves_list_model.dart';
import 'package:mohem_flutter_app/models/get_contact_dff_structure_list.dart';
import 'package:mohem_flutter_app/models/profile/basic_details_dff_structure.dart';
import 'package:mohem_flutter_app/models/profile/get_contact_clos_structure_list.dart';
import 'package:mohem_flutter_app/models/profile/get_contact_details_list.dart';
import 'package:mohem_flutter_app/models/profile/submit_contact_transaction_list_model.dart';
import 'package:mohem_flutter_app/ui/misc/request_submit_screen.dart';
import 'package:mohem_flutter_app/widgets/app_bar_widget.dart';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:mohem_flutter_app/widgets/button/default_button.dart';
import 'package:mohem_flutter_app/widgets/dynamic_forms/dynamic_textfield_widget.dart';
import 'package:easy_localization/src/public_ext.dart';

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

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

class _AddUpdateFamilyMemberState extends State<AddUpdateFamilyMember> {
  List<GetBasicDetDffStructureList?> getBasicDetDffStructureList = [];
  List<GetContactColsStructureList?> getContactColsStructureList = [];
  List<GetContactDffStructureList?> getContactDffStructureList = [];
  List<GetContactDetailsList?> getContactDetailsList = [];
  SubmitContactTransactionList? submitContactTransactionList;
  dynamic args;
  String? date = "MM/DD/YYYY";
  var dateTime = DateTime.now().timeZoneOffset;
  var dateTime1 = DateTime.now().timeZoneName;

  GetApprovesList? getApprovesList;

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

  void callAddAndUpdateFamilyMember() async {
    try {
      Utils.showLoading(context);
      getBasicDetDffStructureList = await ProfileApiClient().getBasicDetDffStructure();
      getContactColsStructureList = await ProfileApiClient().getContactColsStructureList(args['actionType']);
      getContactDffStructureList = await ProfileApiClient().getContactDffStructureList();
      if (args['actionType'] == "ADD") {
        getBasicDetDffStructureList?.forEach((element) {
          element?.getContactDetailsList = new GetContactDetailsList();
        });
        getContactColsStructureList?.forEach((element) {
          element?.getContactDetailsList = new GetContactDetailsList();
        });
        getContactDffStructureList?.forEach((element) {
          element?.getContactDetailsList = new GetContactDetailsList();
        });
      } else if (args['actionType'] == "UPDATE") {
        getContactDetailsList = await ProfileApiClient().getContactDetailsList(args['relationID']);

        getBasicDetDffStructureList?.forEach((element) {
          element?.getContactDetailsList = getContactDetailsList?.singleWhere((userDetail) => userDetail?.aPPLICATIONCOLUMNNAME == element?.aPPLICATIONCOLUMNNAME);
        });
        getContactColsStructureList?.forEach((element) {
          element?.getContactDetailsList = getContactDetailsList?.singleWhere((userDetail) => userDetail?.aPPLICATIONCOLUMNNAME == element?.aPPLICATIONCOLUMNNAME);
        });

        getContactDffStructureList?.forEach((element) {
          element?.getContactDetailsList = getContactDetailsList?.singleWhere((userDetail) => userDetail?.aPPLICATIONCOLUMNNAME == element?.aPPLICATIONCOLUMNNAME);
        });
      }
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  @override
  Widget build(BuildContext context) {
    if (args == null) {
      args = ModalRoute.of(context)!.settings.arguments;
      callAddAndUpdateFamilyMember();
    }
    return Scaffold(
      appBar: AppBarWidget(
        context,
        title: LocaleKeys.profile_familyDetails.tr(),
      ),
      backgroundColor: MyColors.backgroundColor,
      body: args['flag'] == 1
          ? Column(
              children: [
                ListView(physics: const BouncingScrollPhysics(), padding: const EdgeInsets.all(21), children: [
                  ListView.separated(
                      physics: const NeverScrollableScrollPhysics(),
                      shrinkWrap: true,
                      itemBuilder: (BuildContext cxt, int parentIndex) {
                        return parseDynamicFormatTypeCols(getContactColsStructureList![parentIndex], parentIndex);
                      },
                      separatorBuilder: (cxt, index) => 0.height,
                      itemCount: getContactColsStructureList!.length),
                  12.height,
                  ListView.separated(
                      physics: const NeverScrollableScrollPhysics(),
                      shrinkWrap: true,
                      itemBuilder: (BuildContext cxt, int parentIndex) {
                        return parseDynamicFormatTypeBasicDetDff(getBasicDetDffStructureList![parentIndex], parentIndex);
                      },
                      separatorBuilder: (cxt, index) => 0.height,
                      itemCount: getBasicDetDffStructureList!.length),
                  ListView.separated(
                      physics: const NeverScrollableScrollPhysics(),
                      shrinkWrap: true,
                      itemBuilder: (BuildContext cxt, int parentIndex) {
                        return parseDynamicFormatTypeContactDff(getContactDffStructureList![parentIndex], parentIndex);
                      },
                      separatorBuilder: (cxt, index) => 0.height,
                      itemCount: getContactDffStructureList!.length),
                ]).expanded,
                DefaultButton(LocaleKeys.next.tr(), () async {
                  submitUpdateForm();
                }).insideContainer,
              ],
            )
          : args['flag'] == 2
              ? Column(
                  children: [
                    // getContactDetailsList!.isEmpty
                    ListView(physics: const BouncingScrollPhysics(), padding: const EdgeInsets.all(21), children: [
                      ListView.separated(
                          physics: const NeverScrollableScrollPhysics(),
                          shrinkWrap: true,
                          itemBuilder: (BuildContext cxt, int parentIndex) {
                            return parseDynamicFormatTypeCols(getContactColsStructureList![parentIndex], parentIndex);
                          },
                          separatorBuilder: (cxt, index) => 0.height,
                          itemCount: getContactColsStructureList!.length),
                      12.height,
                      ListView.separated(
                          physics: const NeverScrollableScrollPhysics(),
                          shrinkWrap: true,
                          itemBuilder: (BuildContext cxt, int parentIndex) {
                            return parseDynamicFormatTypeBasicDetDff(getBasicDetDffStructureList![parentIndex], parentIndex);
                          },
                          separatorBuilder: (cxt, index) => 0.height,
                          itemCount: getBasicDetDffStructureList!.length),
                      ListView.separated(
                          physics: const NeverScrollableScrollPhysics(),
                          shrinkWrap: true,
                          itemBuilder: (BuildContext cxt, int parentIndex) {
                            return parseDynamicFormatTypeContactDff(getContactDffStructureList![parentIndex], parentIndex);
                          },
                          separatorBuilder: (cxt, index) => 0.height,
                          itemCount: getContactDffStructureList!.length),
                    ]).expanded,
                    DefaultButton(LocaleKeys.next.tr(), () async {
                      submitUpdateForm();
                    }).insideContainer,
                  ],
                )
              : Container(),
    );
  }

  Widget parseDynamicFormatTypeCols(GetContactColsStructureList? model, int index) {
    if (model!.dISPLAYFLAG != "N") {
    } else {
      return const SizedBox();
    }
    if (model.dATATYPE == "VARCHAR2") {
      if (model!.objectValuesList?.isNotEmpty ?? false) {
        return PopupMenuButton(
            child: DynamicTextFieldWidget(
              (model!.sEGMENTPROMPT ?? "") + (model!.rEQUIREDFLAG == "Y" ? "*" : ""),
              model!.getContactDetailsList!.sEGMENTVALUEDSP ?? "",
              isEnable: false,
              isPopup: true,
            ).paddingOnly(bottom: 12),
            itemBuilder: (_) => <PopupMenuItem<int>>[
                  for (int i = 0; i < getContactColsStructureList[index]!.objectValuesList!.length; i++)
                    PopupMenuItem<int>(child: Text(getContactColsStructureList[index]!.objectValuesList![i].mEANING.toString()), value: i),
                ],
            onSelected: (int popupIndex) {
              model.getContactDetailsList!.sEGMENTVALUEDSP = getContactColsStructureList[index]!.objectValuesList![popupIndex].mEANING.toString();
              model.getContactDetailsList!.vARCHAR2VALUE = getContactColsStructureList[index]!.objectValuesList![popupIndex].cODE.toString();
              setState(() {});
            });
      } else {
        return DynamicTextFieldWidget(
          (model!.sEGMENTPROMPT ?? "") + (model!.rEQUIREDFLAG == "Y" ? "*" : ""),
          (model!.getContactDetailsList!.sEGMENTVALUEDSP ?? ""),
          //isInputTypeNum: true,
          onChange: (text) {
            model!.getContactDetailsList!.sEGMENTVALUEDSP = text;
          },
        ).paddingOnly(bottom: 12);
      }
    } else if (model.dATATYPE == "NUMBER") {
      return DynamicTextFieldWidget(
        (model!.sEGMENTPROMPT ?? "") + (model!.rEQUIREDFLAG == "Y" ? "*" : ""),
        (model!.getContactDetailsList!.sEGMENTVALUEDSP ?? ""),
        isInputTypeNum: true,
        onChange: (text) {
          model!.getContactDetailsList!.sEGMENTVALUEDSP = text;
        },
      ).paddingOnly(bottom: 12);
    } else if (model.dATATYPE == "DATE") {
      return DynamicTextFieldWidget(
        (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
        model!.getContactDetailsList!.sEGMENTVALUEDSP ?? "",
        suffixIconData: Icons.calendar_today,
        isEnable: false,
        onTap: () async {
          DateTime dateValue = await _selectDate(context);
          //date = DateFormat('yyyy/MM/dd').format(dateValue);
          date = "2022-10-23T09:17:38.653+03:00";
          //  date = (DateFormat('yyyy-MM-dd').format(dateValue)+"T"+ dateTime.toString() + dateTime1.toString());
          model!.getContactDetailsList!.sEGMENTVALUEDSP = date;
          print(dateTime);
          print(dateTime1);
          print(date);
          setState(() {});
        },
      ).paddingOnly(bottom: 12);
    }
    return Container();
  }

  Widget parseDynamicFormatTypeBasicDetDff(GetBasicDetDffStructureList? model, int index) {
    if (model!.dISPLAYFLAG != "N") {
    } else {
      return const SizedBox();
    }
    if (model!.fORMATTYPE == "C") {
      if (model!.eSERVICESVS?.isNotEmpty ?? false) {
        return PopupMenuButton(
            child: DynamicTextFieldWidget(
              (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
              model.getContactDetailsList!.sEGMENTVALUEDSP ?? "",
              isEnable: false,
              isPopup: true,
            ).paddingOnly(bottom: 12),
            itemBuilder: (_) => <PopupMenuItem<int>>[
                  for (int i = 0; i < getBasicDetDffStructureList[index]!.eSERVICESVS!.length; i++)
                    PopupMenuItem<int>(child: Text(getBasicDetDffStructureList[index]!.eSERVICESVS![i].vALUECOLUMNNAME.toString()), value: i),
                ],
            onSelected: (int popupIndex) {
              model.getContactDetailsList!.sEGMENTVALUEDSP = getBasicDetDffStructureList[index]!.eSERVICESVS![popupIndex].vALUECOLUMNNAME.toString();
              model.getContactDetailsList!.vARCHAR2VALUE = getBasicDetDffStructureList[index]!.eSERVICESVS![popupIndex].iDCOLUMNNAME.toString();

              setState(() {});
            });
      } else {
        return DynamicTextFieldWidget(
          (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
          model.getContactDetailsList!.sEGMENTVALUEDSP ?? "",
          // isInputTypeNum: true,
          onChange: (text) {
            model.getContactDetailsList!.sEGMENTVALUEDSP = text;
          },
        ).paddingOnly(bottom: 12);
      }
    } else if (model.fORMATTYPE == "N") {
      return DynamicTextFieldWidget(
        (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
        model.getContactDetailsList!.sEGMENTVALUEDSP ?? "",
        isInputTypeNum: true,
        onChange: (text) {
          model.getContactDetailsList!.sEGMENTVALUEDSP = text;
        },
      ).paddingOnly(bottom: 12);
    } else if (model.fORMATTYPE == "X") {
      return DynamicTextFieldWidget(
        (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
        model!.getContactDetailsList!.sEGMENTVALUEDSP ?? "",
        suffixIconData: Icons.calendar_today,
        isEnable: false,
        onTap: () async {
          DateTime dateValue = await _selectDate(context);
          date = "2022-10-23T09:17:38.653+03:00";
          // date = (DateFormat('yyyy-MM-dd').format(dateValue) +"T"+ dateTime.toString() + dateTime1.toString());
          // date = DateFormat('yyyy/MM/dd').format(dateValue);
          model!.getContactDetailsList!.sEGMENTVALUEDSP = date;
          setState(() {});
        },
      ).paddingOnly(bottom: 12);
    }
    return Container();
  }

  Widget parseDynamicFormatTypeContactDff(GetContactDffStructureList? model, int index) {
    if (model!.dISPLAYFLAG != "N") {
    } else {
      return const SizedBox();
    }
    if (model!.fORMATTYPE == "C") {
      if (model.eSERVICESVS?.isNotEmpty ?? false) {
        return PopupMenuButton(
            child: DynamicTextFieldWidget(
              (model!.sEGMENTPROMPT ?? "") + (model!.rEQUIREDFLAG == "Y" ? "*" : ""),
              model!.getContactDetailsList!.sEGMENTVALUEDSP ?? "",
              isEnable: false,
              isPopup: true,
            ).paddingOnly(bottom: 12),
            itemBuilder: (_) => <PopupMenuItem<int>>[
                  for (int i = 0; i < getContactDffStructureList[index]!.eSERVICESVS!.length; i++)
                    PopupMenuItem<int>(child: Text(getContactDffStructureList[index]!.eSERVICESVS![i].vALUECOLUMNNAME.toString()), value: i),
                ],
            onSelected: (int popupIndex) {
              model.getContactDetailsList!.sEGMENTVALUEDSP = getContactDffStructureList[index]!.eSERVICESVS![popupIndex].vALUECOLUMNNAME.toString();
              model.getContactDetailsList!.vARCHAR2VALUE = getContactDffStructureList[index]!.eSERVICESVS![popupIndex].iDCOLUMNNAME.toString();
              setState(() {});
            });
      } else {
        return DynamicTextFieldWidget(
          (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
          model.getContactDetailsList!.sEGMENTVALUEDSP ?? "",
          //  isInputTypeNum: true,
          onChange: (text) {
            model.getContactDetailsList!.sEGMENTVALUEDSP = text;
          },
        ).paddingOnly(bottom: 12);
      }
    } else if (model.fORMATTYPE == "N") {
      return DynamicTextFieldWidget(
        (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
        model.getContactDetailsList!.sEGMENTVALUEDSP ?? "",
        isInputTypeNum: true,
        onChange: (text) {
          model.getContactDetailsList!.sEGMENTVALUEDSP = text;
        },
      ).paddingOnly(bottom: 12);
    } else if (model.fORMATTYPE == "X") {
      return DynamicTextFieldWidget(
        (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
        model!.getContactDetailsList!.sEGMENTVALUEDSP ?? "",
        suffixIconData: Icons.calendar_today,
        isEnable: false,
        onTap: () async {
          DateTime dateValue = await _selectDate(context);
          date = "2022-10-23T09:17:38.653+03:00";
          // date = (DateFormat('yyyy-MM-dd').format(dateValue)+"T"+ dateTime.toString() + dateTime1.toString());
          // date = DateFormat('yyyy/MM/dd').format(dateValue);
          model!.getContactDetailsList!.sEGMENTVALUEDSP = date;
          setState(() {});
        },
      ).paddingOnly(bottom: 12);
    }
    return Container();
  }

  DateTime selectedDate = DateTime.now();

  Future<DateTime> _selectDate(BuildContext context) async {
    DateTime time = selectedDate;
    if (!Platform.isIOS) {
      await showCupertinoModalPopup(
        context: context,
        builder: (cxt) => Container(
          height: 250,
          color: Colors.white,
          child: CupertinoDatePicker(
            backgroundColor: Colors.white,
            mode: CupertinoDatePickerMode.date,
            onDateTimeChanged: (value) {
              if (value != null && value != selectedDate) {
                time = value;
              }
            },
            initialDateTime: selectedDate,
          ),
        ),
      );
    } else {
      DateTime? picked = await showDatePicker(context: context, initialDate: selectedDate, initialEntryMode: DatePickerEntryMode.calendarOnly, firstDate: DateTime(2015, 8), lastDate: DateTime(2101));
      if (picked != null && picked != selectedDate) {
        time = picked;
      }
    }
    return time;
  }

  void submitUpdateForm() async {
    // try {
    List<Map<String, dynamic>> values1 = getBasicDetDffStructureList!.map((e) {
      String? dateVal = '';
      String? vatcherVal = '';
      int? numberVal;
      if (e!.fORMATTYPE == 'N') {
        dateVal = null;
        vatcherVal = null;
        numberVal = int.parse(e.getContactDetailsList!.sEGMENTVALUEDSP??"0");
      } else if (e.fORMATTYPE == 'X') {
        dateVal = e!.getContactDetailsList!.sEGMENTVALUEDSP.toString();
        vatcherVal = null;
        numberVal = null;
      } else {
        dateVal = null;
        vatcherVal = e!.getContactDetailsList!.sEGMENTVALUEDSP;
        numberVal = null;
      }
      return ValidateEitTransactionModel(dATEVALUE: dateVal, nAME: e.aPPLICATIONCOLUMNNAME, nUMBERVALUE: numberVal, tRANSACTIONNUMBER: 1, vARCHAR2VALUE: vatcherVal.toString()).toJson();
    }).toList();
    List<Map<String, dynamic>> values2 = getContactDffStructureList!.map((e) {
      String? dateVal = '';
      String? vatcherVal = '';
      int? numberVal;
      if (e!.fORMATTYPE == 'N') {
        dateVal = null;
        vatcherVal = null;
        numberVal = int.parse(e.getContactDetailsList!.sEGMENTVALUEDSP??"0");
      } else if (e.fORMATTYPE == 'X') {
        dateVal = e!.getContactDetailsList!.sEGMENTVALUEDSP;
        vatcherVal = null;
        numberVal = null;
      } else {
        dateVal = null;
        numberVal = null;
        vatcherVal = e!.getContactDetailsList!.sEGMENTVALUEDSP;
      }
      return ValidateEitTransactionModel(dATEVALUE: dateVal, nAME: e.aPPLICATIONCOLUMNNAME, nUMBERVALUE: numberVal, tRANSACTIONNUMBER: 1, vARCHAR2VALUE: vatcherVal.toString()).toJson();
    }).toList();
    List<Map<String, dynamic>> values3 = getContactColsStructureList!.map((e) {
      // String tempVar = e!.getContactDetailsList!.sEGMENTVALUEDSP ?? "";
      String? dateVal = '';
      String? vatcherVal = '';
      int? numberVal;

      print("e.dATATYPE:${e?.dATATYPE}");
      if (e!.dATATYPE == 'VARCHAR2') {
        dateVal = null;
        numberVal = null;
        vatcherVal = e.getContactDetailsList?.sEGMENTVALUEDSP ?? "";
      } else if (e.dATATYPE == 'DATE') {
        dateVal = e.getContactDetailsList!.sEGMENTVALUEDSP.toString();
        print("dateVal:${dateVal ?? ""}");
        vatcherVal = null;
        numberVal = null;
      } else if (e.dATATYPE == 'NUMBER') {
        dateVal = null;
        vatcherVal = null;
        numberVal = int.parse(e.getContactDetailsList!.sEGMENTVALUEDSP??"0");
      } else {}
      return ValidateEitTransactionModel(dATEVALUE: dateVal, nAME: e.aPPLICATIONCOLUMNNAME, nUMBERVALUE: numberVal, tRANSACTIONNUMBER: 1, vARCHAR2VALUE: vatcherVal).toJson();
    }).toList();
    List<Map<String, dynamic>> valuesFinal = [...values1, ...values2, ...values3];
    Utils.showLoading(context);
    submitContactTransactionList = await ProfileApiClient().submitContactTransactionAddAndUpdate(args['actionType'], args['relationID'] ?? null, valuesFinal);
    var transactionId = submitContactTransactionList!.pTRANSACTIONID;
    var itemKey = submitContactTransactionList!.pITEMKEY;
    Utils.hideLoading(context);
    Navigator.pushNamed(context, AppRoutes.requestSubmitScreen,
        arguments: RequestSubmitScreenParams(LocaleKeys.profile_familyDetails.tr(), transactionId!.toInt(), itemKey.toString(), 'family_member'));
    setState(() {});
    // } catch (ex) {
    //   Utils.hideLoading(context);
    //   Utils.handleException(ex, context, null);
    // }
  }
}
