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/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_basic_details.model.dart';
import 'package:mohem_flutter_app/models/profile/basic_details_cols_structions.dart';
import 'package:mohem_flutter_app/models/profile/basic_details_dff_structure.dart';
import 'package:mohem_flutter_app/models/profile/submit_basic_details_transaction_model.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<GetEmployeeBasicDetailsList>? getEmployeeBasicDetailsList;

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

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

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

class _DynamicInputScreenState extends State<DynamicInputScreenProfile> {
  GenericResponseModel? genericResponseModel;
  List<GetBasicDetDffStructureList>? getBasicDetDffStructureList;
  List<GetBasicDetColsStructureList>? getBasicDetColsStructureList;
  DynamicProfileParams? dynamicParams;

  String dESCFLEXCONTEXTCODE = "";

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

  void getTransactionsStructure() async {
    try {
      Utils.showLoading(context);
      genericResponseModel = await ProfileApiClient().getDffStructure("BASIC_DETAILS", dynamicParams!.uRL, dynamicParams!.requestID);
      getBasicDetDffStructureList = genericResponseModel?.getBasicDetDffStructureList ?? [];
      genericResponseModel = await ProfileApiClient().getColStructure(dynamicParams!.dynamicId, 'GET_BASIC_DET_COLS_STRUCTURE', dynamicParams!.requestID);
      getBasicDetColsStructureList = genericResponseModel?.getBasicDetColsStructureList ?? [];

      if (dynamicParams!.correctOrNew == 1) {
        getBasicDetDffStructureList?.forEach((GetBasicDetDffStructureList element) {
          element.userBasicDetail =
              dynamicParams!.getEmployeeBasicDetailsList!.singleWhere((GetEmployeeBasicDetailsList userDetail) => userDetail.aPPLICATIONCOLUMNNAME == element.aPPLICATIONCOLUMNNAME);
        });
        getBasicDetColsStructureList?.forEach((GetBasicDetColsStructureList element) {
          element.userBasicDetail =
              dynamicParams!.getEmployeeBasicDetailsList!.singleWhere((GetEmployeeBasicDetailsList userDetail) => userDetail.aPPLICATIONCOLUMNNAME == element.aPPLICATIONCOLUMNNAME);
          if (element.objectValuesList != null) {
            ObjectValuesList dropDownListValue = element.objectValuesList!.singleWhere((ObjectValuesList dropdown) => dropdown.cODE == element.userBasicDetail!.vARCHAR2VALUE);
            element.userBasicDetail!.sEGMENTVALUEDSP = dropDownListValue.mEANING;
          }
        });
      } else {
        getBasicDetDffStructureList?.forEach((element) {
          element.userBasicDetail = new GetEmployeeBasicDetailsList();
        });
        getBasicDetColsStructureList?.forEach((element) {
          element.userBasicDetail = GetEmployeeBasicDetailsList();
        });
      }

      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void calGetValueSetValues(GetBasicDetDffStructureList structureList) async {
    try {
      Utils.showLoading(context);
      String segmentId = structureList.cHILDSEGMENTSVS!;
      List<GetBasicDetDffStructureList> filteredList = getBasicDetDffStructureList?.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 = getBasicDetDffStructureList!.indexWhere((element) => element.sEGMENTNAME == structureList.cHILDSEGMENTSVS);
      if (genericResponseModel.isNotEmpty) getBasicDetDffStructureList![index].eSERVICESVS!.addAll(genericResponseModel);
      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: [
          (getBasicDetDffStructureList == null && getBasicDetColsStructureList == null
                  ? const SizedBox()
                  : (getBasicDetDffStructureList!.isEmpty && getBasicDetColsStructureList!.isEmpty
                      ? Utils.getNoDataWidget(context)
                      : ListView(
                          physics: const BouncingScrollPhysics(),
                          padding: const EdgeInsets.all(21),
                          children: [
                            ListView.separated(
                                physics: const NeverScrollableScrollPhysics(),
                                shrinkWrap: true,
                                itemBuilder: (BuildContext cxt, int parentIndex) {
                                  return parseDynamicFormatTypeCols(getBasicDetColsStructureList![parentIndex], parentIndex);
                                },
                                separatorBuilder: (cxt, index) => 0.height,
                                itemCount: getBasicDetColsStructureList!.length),
                            12.height,
                            ListView.separated(
                                physics: const NeverScrollableScrollPhysics(),
                                shrinkWrap: true,
                                itemBuilder: (BuildContext cxt, int parentIndex) {
                                  return parseDynamicFormatType(getBasicDetDffStructureList![parentIndex], parentIndex);
                                },
                                separatorBuilder: (cxt, index) => 0.height,
                                itemCount: getBasicDetDffStructureList!.length),
                          ],
                        )))
              .expanded,
          // 12.height,
          DefaultButton(
            LocaleKeys.next.tr(),
            () => {validateTransaction()},
          ).insideContainer,
        ],
      ),
    );
  }

  Widget parseDynamicFormatType(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.userBasicDetail?.aPPLICATIONCOLUMNNAME ?? "",
              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) {
              getBasicDetDffStructureList![index].userBasicDetail!.sEGMENTVALUEDSP = model.eSERVICESVS![popupIndex].vALUECOLUMNNAME;
              getBasicDetDffStructureList![index].userBasicDetail!.aPPLICATIONCOLUMNNAME = model.eSERVICESVS![popupIndex].dESCRIPTION;
              setState(() {});
            });
      }

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

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [],
    ).objectContainerView();
  }

  Widget parseDynamicFormatTypeCols(GetBasicDetColsStructureList 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" ? "*" : ""),
            getBasicDetColsStructureList![index].userBasicDetail!.sEGMENTVALUEDSP ?? "",
            isEnable: false,
            isPopup: true,
          ).paddingOnly(bottom: 12),
          itemBuilder: (_) => <PopupMenuItem<int>>[
            for (int i = 0; i < model.objectValuesList!.length; i++) PopupMenuItem<int>(child: Text(model.objectValuesList![i].mEANING!), value: i),
          ],
          onSelected: (int popupIndex) {
            if (model.objectValuesList![popupIndex].cODE != '') {
              ESERVICESDV eservicesdv =
                  ESERVICESDV(pIDCOLUMNNAME: model.objectValuesList![popupIndex].mEANING, pRETURNMSG: "null", pRETURNSTATUS: model.oBJECTNAME, pVALUECOLUMNNAME: model.aPPLICATIONCOLUMNNAME);
              getBasicDetColsStructureList![index].userBasicDetail!.sEGMENTVALUEDSP = model.objectValuesList![popupIndex].mEANING;
              getBasicDetColsStructureList![index].userBasicDetail!.vARCHAR2VALUE = model.objectValuesList![popupIndex].cODE;
            } else {
              ESERVICESDV eservicesdv =
                  ESERVICESDV(pIDCOLUMNNAME: model.objectValuesList![popupIndex].dESCRIPTION, pRETURNMSG: "null", pRETURNSTATUS: model.oBJECTNAME, pVALUECOLUMNNAME: model.aPPLICATIONCOLUMNNAME);
              getBasicDetColsStructureList![index].userBasicDetail!.sEGMENTVALUEDSP = model.objectValuesList![popupIndex].dESCRIPTION;
              getBasicDetColsStructureList![index].userBasicDetail!.vARCHAR2VALUE = model.objectValuesList![popupIndex].mEANING;
            }
            setState(() {});
          },
        );
      }

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

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [],
    ).objectContainerView();
  }

  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 validateTransaction() async {
    try {
      Utils.showLoading(context);
      int numberValue = 0;
      List<Map<String, dynamic>> values = getBasicDetDffStructureList!.map((e) {
        String tempVar = e.userBasicDetail!.vARCHAR2VALUE ?? "";

        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('yyyy/MM/dd HH:mm:ss').format(date);
          }
        }
        return ValidateEitTransactionModel(dATEVALUE: null, nAME: e.aPPLICATIONCOLUMNNAME, nUMBERVALUE: null, tRANSACTIONNUMBER: 1, vARCHAR2VALUE: tempVar.toString()).toJson();
      }).toList();

      values.add(ValidateEitTransactionModel(dATEVALUE: null, nAME: "PEI_ACTION", nUMBERVALUE: null, tRANSACTIONNUMBER: 1, vARCHAR2VALUE: "NEW_ROW").toJson());
      values.add(ValidateEitTransactionModel(dATEVALUE: null, nAME: "PEI_EXTRA_INFO_ID", nUMBERVALUE: -1, tRANSACTIONNUMBER: 1, vARCHAR2VALUE: null).toJson());
      //values.add(ValidateEitTransactionModel(dATEVALUE: null, nAME: "PEI_OBJECT_VERSION_NUMBER", nUMBERVALUE: 0, tRANSACTIONNUMBER: 1, vARCHAR2VALUE: null).toJson());
      List<Map<String, dynamic>> valuesCols = getBasicDetColsStructureList!.map((e) {
        if (e.dATATYPE == 'NUMBER') {
          numberValue = e.userBasicDetail!.nUMBERVALUE!;
        }
        return ValidateEitTransactionModel(
                dATEVALUE: e.userBasicDetail!.dATEVALUE ?? "", nAME: e.aPPLICATIONCOLUMNNAME, nUMBERVALUE: numberValue, tRANSACTIONNUMBER: 1, vARCHAR2VALUE: e.userBasicDetail!.vARCHAR2VALUE ?? "")
            .toJson();
      }).toList();
      List<Map<String, dynamic>> transactionValues = new List.from(values)..addAll(valuesCols);
      print(transactionValues);

      SubmitBasicDetailsTransactionList submitBasicDetails =
          await ProfileApiClient().submitBasicDetailsTransaction(dESCFLEXCONTEXTCODE, dynamicParams!.dynamicId, transactionValues, dynamicParams!.correctOrNew);
      print(submitBasicDetails);
      Utils.hideLoading(context);

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