import 'dart:io';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mohem_flutter_app/api/my_attendance_api_client.dart';
import 'package:mohem_flutter_app/api/profile_api_client.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/get_set_values_request_model.dart';
import 'package:mohem_flutter_app/models/dyanmic_forms/validate_eit_transaction_model.dart';
import 'package:mohem_flutter_app/models/generic_response_model.dart';
import 'package:mohem_flutter_app/models/get_eit_dff_structure_list_model.dart';
import 'package:mohem_flutter_app/models/get_employee_address_model.dart';
import 'package:mohem_flutter_app/models/profile/get_address_dff_structure_list.dart';
import 'package:mohem_flutter_app/models/profile/get_countries_list_model.dart';
import 'package:mohem_flutter_app/models/profile/submit_address_transaction.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 DynamicProfileParams {
  String title;
  String dynamicId;
  String uRL;
  String requestID;
  String colsURL;
  int correctOrNew;
  List<GetEmployeeAddressList>? getEmployeeAddressList;

  DynamicProfileParams(this.title, this.dynamicId,
      {this.uRL = 'GET_EIT_DFF_STRUCTURE', this.requestID = '', this.colsURL = '', this.getEmployeeAddressList = const <GetEmployeeAddressList>[], this.correctOrNew = 2});
}

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

  @override
  _DynamicInputScreenState createState() {
    return _DynamicInputScreenState();
  }
}

class _DynamicInputScreenState extends State<DynamicInputScreenAddress> {
  GenericResponseModel? genericResponseModel;
  List<GetAddressDffStructureList>? getAddressDffStructureList;
  SubmitAddressTransaction submitPhoneNumbers = SubmitAddressTransaction();
  DynamicProfileParams? dynamicParams;
  List<GetCountriesListModel> countriesList = [];
  String dESCFLEXCONTEXTCODE = "";
  String countryCode = 'SA';
  String effectiveDate = '';

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

  void getTransactionsStructure() async {
    try {
      Utils.showLoading(context);
      genericResponseModel = await ProfileApiClient().getDffStructure(dynamicParams!.dynamicId, dynamicParams!.uRL, dynamicParams!.requestID);
      getAddressDffStructureList = genericResponseModel?.getAddressDffStructureList ?? [];

      if (dynamicParams!.correctOrNew == 1) {
        getAddressDffStructureList?.forEach((element) {
          dynamicParams!.getEmployeeAddressList!.forEach((userDetail) {
            if (userDetail.aPPLICATIONCOLUMNNAME == element.aPPLICATIONCOLUMNNAME) {
              element.getEmployeeAddressList = userDetail;
            }
          });
        });
      } else {
        getAddressDffStructureList!.insert(0, GetAddressDffStructureList(fORMATTYPE: 'X', sEGMENTPROMPT: LocaleKeys.profile_effectiveDate.tr()));
        countriesList = await ProfileApiClient().getCountriesList();
        List<ESERVICESVS> eSerivceList = [];
        countriesList.forEach((element) {
          eSerivceList.add(ESERVICESVS(
            dESCRIPTION: element.cOUNTRYCODE,
            vALUECOLUMNNAME: element.cOUNTRYNAME,
          ));
        });
        getAddressDffStructureList!
            .insert(1, GetAddressDffStructureList(fORMATTYPE: 'C', sEGMENTPROMPT: LocaleKeys.profile_country.tr(), eSERVICESVS: eSerivceList, getEmployeeAddressList: GetEmployeeAddressList()));
      }
      print(getAddressDffStructureList);
      // genericResponseModel = await ProfileApiClient().getColStructure(dynamicParams!.dynamicId, 'GET_BASIC_DET_COLS_STRUCTURE', dynamicParams!.requestID);
      // getBasicDetColsStructureList = genericResponseModel?.getBasicDetColsStructureList ?? [];
      // getBasicDetColsStructureList?.forEach((element) {
      //   element.userBasicDetail = dynamicParams!.getEmployeeBasicDetailsList!.singleWhere((userDetail) => userDetail.aPPLICATIONCOLUMNNAME == element.aPPLICATIONCOLUMNNAME);
      // });
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void calGetValueSetValues(GetAddressDffStructureList structureList) async {
    try {
      Utils.showLoading(context);
      String segmentId = structureList.cHILDSEGMENTSVS!;
      List<GetAddressDffStructureList> filteredList = getAddressDffStructureList?.where((element) => element.cHILDSEGMENTSVS == segmentId).toList() ?? [];
      List<Map<String, dynamic>> values = filteredList
          .map((e) => GetSetValuesRequestModel(
                  sEGMENTNAME: e.sEGMENTNAME, vALUECOLUMNNAME: e.eSERVICESDV!.pVALUECOLUMNNAME, dESCRIPTION: "", iDCOLUMNNAME: e.eSERVICESDV!.pIDCOLUMNNAME, fLEXVALUESETNAME: e.fLEXVALUESETNAME)
              .toJson())
          .toList();
      List<ESERVICESVS> genericResponseModel = await MyAttendanceApiClient().getValueSetValues(structureList.cHILDSEGMENTSVS!, structureList.dESCFLEXCONTEXTCODE!, structureList.dESCFLEXNAME!, values);

      int index = getAddressDffStructureList!.indexWhere((element) => element.sEGMENTNAME == structureList.cHILDSEGMENTSVS);
      if (genericResponseModel.isNotEmpty) getAddressDffStructureList![index].eSERVICESVS!.addAll(genericResponseModel);
      //   getEitDffStructureList = genericResponseModel?.getEITDFFStructureList ?? [];
      //getEitDffStructureList = getEitDffStructureList!.where((element) => element.dISPLAYFLAG != "N").toList();
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

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

  @override
  Widget build(BuildContext context) {
    if (dynamicParams == null) {
      dynamicParams = ModalRoute.of(context)!.settings.arguments as DynamicProfileParams;
      getTransactionsStructure();
    }
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBarWidget(
        context,
        title: dynamicParams!.title,
      ),
      body: Column(
        children: [
          (getAddressDffStructureList == null
                  ? const SizedBox()
                  : (getAddressDffStructureList!.isEmpty
                      ? LocaleKeys.noDataAvailable.tr().toText16().center
                      : ListView(
                          physics: const BouncingScrollPhysics(),
                          padding: const EdgeInsets.all(21),
                          children: [
                            12.height,
                            ListView.separated(
                                physics: const NeverScrollableScrollPhysics(),
                                shrinkWrap: true,
                                itemBuilder: (BuildContext cxt, int parentIndex) {
                                  return parseDynamicFormatType(getAddressDffStructureList![parentIndex], parentIndex);
                                },
                                separatorBuilder: (cxt, index) => 0.height,
                                itemCount: getAddressDffStructureList!.length),
                          ],
                        )))
              .expanded,
          // 12.height,
          DefaultButton(
            LocaleKeys.next.tr(),
            (getAddressDffStructureList ?? []).isEmpty ? null : () => {validateTransaction()},
          ).insideContainer,
        ],
      ),
    );
  }

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

        return DynamicTextFieldWidget(
          (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
          model.getEmployeeAddressList?.sEGMENTVALUEDSP ?? "",
          isReadOnly: model.rEADONLY == "Y",
          onChange: (text) {
            model.getEmployeeAddressList?.sEGMENTVALUEDSP = text;
          },
        ).paddingOnly(bottom: 12);
      } else if (model.fORMATTYPE == "N") {
        if (model.eSERVICESVS?.isNotEmpty ?? false) {
          return PopupMenuButton(
              child: DynamicTextFieldWidget((model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""), model?.getEmployeeAddressList!.sEGMENTVALUEDSP ?? "",
                      isEnable: false, isPopup: true, isInputTypeNum: true)
                  .paddingOnly(bottom: 12),
              itemBuilder: (_) => <PopupMenuItem<int>>[
                    for (int i = 0; i < model.eSERVICESVS!.length; i++) PopupMenuItem<int>(child: Text(model.eSERVICESVS![i].dESCRIPTION!), value: i),
                  ],
              onSelected: (int popupIndex) {
                model?.getEmployeeAddressList!.sEGMENTVALUEDSP = model.eSERVICESVS![popupIndex].dESCRIPTION;
                model?.getEmployeeAddressList!.vARCHAR2VALUE = model.eSERVICESVS![popupIndex].vALUECOLUMNNAME;
                setState(() {});
              });
        }

        return DynamicTextFieldWidget(
          (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
          model.getEmployeeAddressList?.sEGMENTVALUEDSP ?? "",
          isReadOnly: model.rEADONLY == "Y",
          onChange: (text) {
            model.getEmployeeAddressList?.sEGMENTVALUEDSP = text;
          },
        ).paddingOnly(bottom: 12);
      } else if (model.fORMATTYPE == "X") {
        return DynamicTextFieldWidget(
          (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
          model.eSERVICESDV?.pIDCOLUMNNAME ?? (getAddressDffStructureList![index].dESCFLEXCONTEXTNAME ?? ""),
          suffixIconData: Icons.calendar_today,
          isEnable: false,
          onTap: () async {
            DateTime date = await _selectDate(context);
            DateTime date1 = DateTime(date.year, date.month, date.day);
            getAddressDffStructureList![index].dESCFLEXCONTEXTNAME = date.toString();
            ESERVICESDV eservicesdv = ESERVICESDV(
                pIDCOLUMNNAME: DateFormat('yyyy-MM-dd').format(date1),
                pRETURNMSG: "null",
                pRETURNSTATUS: getAddressDffStructureList![index].dEFAULTVALUE,
                pVALUECOLUMNNAME: DateFormat('yyyy-MM-ddThh:mm:ss.s').format(date));
            getAddressDffStructureList![index].eSERVICESDV = eservicesdv;
            setState(() {});
            if (model.cHILDSEGMENTSVSSplited?.isNotEmpty ?? false) {
              calGetValueSetValues(model);
            }
          },
        ).paddingOnly(bottom: 12);
      }

      return const SizedBox();
    } else {
      return const SizedBox();
    }
  }

  void validateTransaction() async {
    try {
      Utils.showLoading(context);
      List<Map<String, dynamic>> values = getAddressDffStructureList!.map((e) {
        String tempVar = '';
        if (e.fORMATTYPE == "X") {
          // for date format type, date format is changed
          tempVar = e.eSERVICESDV?.pVALUECOLUMNNAME ?? "";

          if (tempVar.isNotEmpty) {
            DateTime date = DateFormat('yyyy-MM-dd').parse(tempVar);
            tempVar = DateFormat('dd/MMM/yyy').format(date);
            if (e.aPPLICATIONCOLUMNNAME == null) {
              effectiveDate = tempVar;
            }
          }
        } else if (e.eSERVICESVS?.isNotEmpty ?? false) {
          tempVar = e.getEmployeeAddressList!.vARCHAR2VALUE!;
          if (e.aPPLICATIONCOLUMNNAME == null) {
            countryCode = tempVar;
          }
        } else {
          tempVar = e.getEmployeeAddressList!.sEGMENTVALUEDSP ?? "";
        }

        return ValidateEitTransactionModel(dATEVALUE: null, nAME: e.aPPLICATIONCOLUMNNAME, nUMBERVALUE: null, tRANSACTIONNUMBER: 1, vARCHAR2VALUE: tempVar.toString()).toJson();
      }).toList();

      submitPhoneNumbers = await ProfileApiClient().submitAddressTransaction(dESCFLEXCONTEXTCODE, dynamicParams!.dynamicId, values, dynamicParams!.correctOrNew, countryCode, effectiveDate);
      print(values);
      Utils.hideLoading(context);

      Navigator.pushNamed(context, AppRoutes.requestSubmitScreen,
          arguments: RequestSubmitScreenParams(dynamicParams!.title, submitPhoneNumbers.pTRANSACTIONID!, submitPhoneNumbers.pITEMKEY!, 'address'));
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  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;
  }
}
