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_requests_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/validate_eit_transaction_model.dart';
import 'package:mohem_flutter_app/models/get_eit_dff_structure_list_model.dart';
import 'package:mohem_flutter_app/models/my_requests/get_ccp_transactions_model.dart';
import 'package:mohem_flutter_app/models/my_requests/get_ccp_transations_list_model.dart';
import 'package:mohem_flutter_app/models/my_requests/get_concurrent_programs_model.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 NewRequest extends StatefulWidget {
  const NewRequest({Key? key}) : super(key: key);

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

class _NewRequestState extends State<NewRequest> {
  List<GetConcurrentProgramsModel> getConcurrentProgramsList = [];
  GetConcurrentProgramsModel? selectedConcurrentProgramList;
  SubmitCcpTransactionList? submitCcpTransactionList;
  List<GetCCPTransactionsModel> getCCPTransactionsList = [];
  List<GetEITDFFStructureList>? getCCPDFFStructureModelList;

  DateTime selectedDate = DateTime.now();

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBarWidget(
        context,
        title: LocaleKeys.concurrentReports,
      ),
      body: Column(
        children: [
          ListView(
            padding: const EdgeInsets.all(21),
            physics: const BouncingScrollPhysics(),
            children: [
              PopupMenuButton(
                  child: DynamicTextFieldWidget(
                    LocaleKeys.templateName.tr(),
                    selectedConcurrentProgramList?.uSERCONCURRENTPROGRAMNAME ?? LocaleKeys.selectTemplate.tr(),
                    isEnable: false,
                    isPopup: true,
                    isInputTypeNum: true,
                    isReadOnly: false,
                  ).paddingOnly(bottom: 12),
                  itemBuilder: (_) => <PopupMenuItem<int>>[
                        for (int i = 0; i < getConcurrentProgramsList!.length; i++) PopupMenuItem<int>(child: Text(getConcurrentProgramsList![i].uSERCONCURRENTPROGRAMNAME!), value: i),
                      ],
                  onSelected: (int popupIndex) {
                    selectedConcurrentProgramList = getConcurrentProgramsList![popupIndex];
                    getCCPDFFStructure(selectedConcurrentProgramList?.cONCURRENTPROGRAMNAME);
                    setState(() {});
                  }),
              getCCPDFFStructureModelList == null
                  ? const SizedBox()
                  : (getCCPDFFStructureModelList!.isEmpty
                      ? LocaleKeys.noDataAvailable.tr().toText16().center
                      : ListView.separated(
                          physics: const NeverScrollableScrollPhysics(),
                          shrinkWrap: true,
                          padding: const EdgeInsets.all(0),
                          itemBuilder: (cxt, int parentIndex) => parseDynamicFormatType(getCCPDFFStructureModelList![parentIndex], parentIndex),
                          separatorBuilder: (cxt, index) => 0.height,
                          itemCount: getCCPDFFStructureModelList!.length,
                        )),
            ],
          ).expanded,
          1.divider,
          DefaultButton(LocaleKeys.submit.tr(), () {
            // todo need to add submit method
            openNewRequest();
          }).insideContainer,
        ],
      ),
    );
  }

  void openNewRequest() async {
    try {
      List<Map<String, dynamic>> values = getCCPDFFStructureModelList!.map((e) {
        String? dateVal = '';
        String? vatcherVal = '';
        int? numberVal;
        if (e!.fORMATTYPE == 'N') {
          dateVal = null;
          vatcherVal = e.eSERVICESDV!.pIDCOLUMNNAME;
          numberVal = null;
        } else if (e.fORMATTYPE == 'X') {
          dateVal = null;
          vatcherVal = e.eSERVICESDV!.pIDCOLUMNNAME;
          numberVal = null;
        } else {
          dateVal = null;
          numberVal = null;
          vatcherVal = null;
        }
        return ValidateEitTransactionModel(dATEVALUE: dateVal, nAME: e.aPPLICATIONCOLUMNNAME, nUMBERVALUE: numberVal, tRANSACTIONNUMBER: 1, vARCHAR2VALUE: vatcherVal.toString()).toJson();
      }).toList();
      Utils.showLoading(context);
      submitCcpTransactionList = await MyRequestsApiClient().getSubmitNewRequest(values);
      getCCPTransactionsList = await MyRequestsApiClient().getCcpTransactions(values);
      Utils.hideLoading(context);
      Navigator.pushNamed(
        context,
        AppRoutes.myRequests,
      );
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getConcurrentPrograms() async {
    try {
      Utils.showLoading(context);
      getConcurrentProgramsList = await MyRequestsApiClient().getConcurrentPrograms();
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getCCPDFFStructure(String? templateName) async {
    try {
      Utils.showLoading(context);
      getCCPDFFStructureModelList = await MyRequestsApiClient().getCCPDFFStructure(templateName);
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  Widget parseDynamicFormatType(GetEITDFFStructureList model, int index) {
    if (model.dISPLAYFLAG != "N") {
      if (model.vALIDATIONTYPE == "N") {
        if (model.fORMATTYPE == "C") {
          return DynamicTextFieldWidget(
            (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
            model.eSERVICESDV?.pIDCOLUMNNAME ?? "",
            isReadOnly: model.rEADONLY == "Y",
            onChange: (text) {
              model.fieldAnswer = text;
              model.eSERVICESDV ??= ESERVICESDV();
              model.eSERVICESDV!.pIDCOLUMNNAME = text;
            },
          ).paddingOnly(bottom: 12);
        } else if (model.fORMATTYPE == "N") {
          return DynamicTextFieldWidget(
            (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
            model.eSERVICESDV?.pIDCOLUMNNAME ?? "",
            isReadOnly: model.rEADONLY == "Y",
            isInputTypeNum: true,
            onChange: (text) {
              model.fieldAnswer = text;
              model.eSERVICESDV ??= ESERVICESDV();
              model.eSERVICESDV!.pIDCOLUMNNAME = text;
            },
          ).paddingOnly(bottom: 12);
        } else if (model.fORMATTYPE == "X") {
          String displayText = model.eSERVICESDV?.pIDCOLUMNNAME ?? (getCCPDFFStructureModelList![index].fieldAnswer ?? "");
          if (getCCPDFFStructureModelList![index].isDefaultTypeIsCDPS) {
            if (displayText.contains(" 00:00:00")) {
              displayText = displayText.replaceAll(" 00:00:00", "");
            }
            if (!displayText.contains("-")) {
              displayText = DateFormat('yyyy-MM-dd').format(DateFormat("yyyy/MM/dd").parse(displayText));
            }
          }
          return DynamicTextFieldWidget(
            (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
            displayText.isEmpty ? LocaleKeys.pleaseSelectDate.tr() : displayText,
            suffixIconData: Icons.calendar_today,
            isEnable: false,
            onTap: () async {
              if ((getCCPDFFStructureModelList![index].eSERVICESDV?.pVALUECOLUMNNAME != null)) {
                if (getCCPDFFStructureModelList![index].isDefaultTypeIsCDPS) {
                  selectedDate = DateFormat("yyyy/MM/dd").parse(getCCPDFFStructureModelList![index].eSERVICESDV!.pVALUECOLUMNNAME!.replaceAll('/"', '').replaceAll(" 00:00:00", ""));
                } else {
                  selectedDate = DateTime.parse(getCCPDFFStructureModelList![index].eSERVICESDV!.pVALUECOLUMNNAME!);
                }
              }
              DateTime date = await _selectDate(context);
              DateTime date1 = DateTime(date.year, date.month, date.day);
              // getEitDffStructureList![index].fieldAnswer = date.toString();
              ESERVICESDV eservicesdv;
              if (getCCPDFFStructureModelList![index].isDefaultTypeIsCDPS) {
                eservicesdv = ESERVICESDV(
                    pIDCOLUMNNAME: DateFormat('yyyy/MM/dd HH:MM:SS').format(date1),
                    pRETURNMSG: "null",
                    pRETURNSTATUS: getCCPDFFStructureModelList![index].dEFAULTVALUE,
                    pVALUECOLUMNNAME: getCCPDFFStructureModelList![index].isDefaultTypeIsCDPS ? DateFormat('yyyy/MM/dd HH:MM:SS').format(date) : DateFormat('yyyy-MM-ddThh:mm:ss.s').format(date));
              } else {
                eservicesdv = ESERVICESDV(
                    pIDCOLUMNNAME: DateFormat('yyyy-MM-dd').format(date1),
                    pRETURNMSG: "null",
                    pRETURNSTATUS: getCCPDFFStructureModelList![index].dEFAULTVALUE,
                    pVALUECOLUMNNAME: getCCPDFFStructureModelList![index].isDefaultTypeIsCDPS ? DateFormat('yyyy-MM-dd hh:mm:ss').format(date) : DateFormat('yyyy-MM-ddThh:mm:ss.s').format(date));
              }
              getCCPDFFStructureModelList![index].eSERVICESDV = eservicesdv;
              setState(() {});
              if (model.cHILDSEGMENTSDVSplited?.isNotEmpty ?? false) {
                // calGetValueSetValues(model);
              }
            },
          ).paddingOnly(bottom: 12);
        } else if (model.fORMATTYPE == "Y") {
          String displayText = model.eSERVICESDV?.pIDCOLUMNNAME ?? (getCCPDFFStructureModelList![index].fieldAnswer ?? "");
          if (getCCPDFFStructureModelList![index].isDefaultTypeIsCDPS) {
            if (displayText.contains(" 00:00:00")) {
              displayText = displayText.replaceAll(" 00:00:00", "");
            }
            if (!displayText.contains("-")) {
              displayText = DateFormat('yyyy-MM-dd').format(DateFormat("yyyy/MM/dd").parse(displayText));
            }
          }
          return DynamicTextFieldWidget(
            (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
            displayText,
            suffixIconData: Icons.calendar_today,
            isEnable: false,
            onTap: () async {
              if ((getCCPDFFStructureModelList![index].eSERVICESDV?.pVALUECOLUMNNAME != null)) {
                if (getCCPDFFStructureModelList![index].isDefaultTypeIsCDPS) {
                  String tempDate = getCCPDFFStructureModelList![index].eSERVICESDV!.pVALUECOLUMNNAME!;
                  if (tempDate.contains("00:00:00")) {
                    tempDate = tempDate.replaceAll("00:00:00", '').trim();
                  }
                  selectedDate = DateFormat("yyyy/MM/dd").parse(tempDate);
                } else {
                  selectedDate = DateTime.parse(getCCPDFFStructureModelList![index].eSERVICESDV!.pVALUECOLUMNNAME!);
                }
              }
              DateTime date = await _selectDate(context);
              DateTime date1 = DateTime(date.year, date.month, date.day);
              // getEitDffStructureList![index].fieldAnswer = date.toString();
              ESERVICESDV eservicesdv;
              if (getCCPDFFStructureModelList![index].isDefaultTypeIsCDPS) {
                eservicesdv = ESERVICESDV(
                    pIDCOLUMNNAME: DateFormat('yyyy/MM/dd HH:MM:SS').format(date1),
                    pRETURNMSG: "null",
                    pRETURNSTATUS: getCCPDFFStructureModelList![index].dEFAULTVALUE,
                    pVALUECOLUMNNAME: getCCPDFFStructureModelList![index].isDefaultTypeIsCDPS ? DateFormat('yyyy-MM-dd HH:MM:SS').format(date) : DateFormat('yyyy-MM-ddThh:mm:ss.s').format(date));
              } else {
                eservicesdv = ESERVICESDV(
                    pIDCOLUMNNAME: DateFormat('yyyy-MM-dd').format(date1),
                    pRETURNMSG: "null",
                    pRETURNSTATUS: getCCPDFFStructureModelList![index].dEFAULTVALUE,
                    pVALUECOLUMNNAME: getCCPDFFStructureModelList![index].isDefaultTypeIsCDPS ? DateFormat('yyyy-MM-dd hh:mm:ss').format(date) : DateFormat('yyyy-MM-ddThh:mm:ss.s').format(date));
              }

              getCCPDFFStructureModelList![index].eSERVICESDV = eservicesdv;
              setState(() {});
              if (model.cHILDSEGMENTSDVSplited?.isNotEmpty ?? false) {
                if (getCCPDFFStructureModelList![index].isDefaultTypeIsCDPS) {
                  // calGetValueSetValues(model);
                } else {}
              }
            },
          ).paddingOnly(bottom: 12);
        }
      } else {
        return PopupMenuButton(
            child: DynamicTextFieldWidget(
              (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
              model.eSERVICESDV?.pVALUECOLUMNNAME ?? "",
              isEnable: false,
              isPopup: true,
              isInputTypeNum: true,
              isReadOnly: model.rEADONLY == "Y",
            ).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 popipIndex) {
              ESERVICESDV eservicesdv = ESERVICESDV(
                  pIDCOLUMNNAME: model.eSERVICESVS![popipIndex].iDCOLUMNNAME,
                  pRETURNMSG: "null",
                  pRETURNSTATUS: getCCPDFFStructureModelList![popipIndex].dEFAULTVALUE,
                  pVALUECOLUMNNAME: model.eSERVICESVS![popipIndex].vALUECOLUMNNAME);
              getCCPDFFStructureModelList![index].eSERVICESDV = eservicesdv;
              setState(() {});
              if (model.cHILDSEGMENTSDVSplited?.isNotEmpty ?? false) {
                // getDefaultValues(model);
              }
            });
      }
    } else {
      return const SizedBox();
    }
    if (model.fORMATTYPE == "N") {
      if (model.eSERVICESVS?.isNotEmpty ?? false) {
        return PopupMenuButton(
            child: DynamicTextFieldWidget(
              (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
              model.eSERVICESDV?.pVALUECOLUMNNAME ?? "",
              isEnable: false,
              isPopup: true,
              isInputTypeNum: true,
              isReadOnly: model.rEADONLY == "Y",
            ).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 popipIndex) {
              ESERVICESDV eservicesdv = ESERVICESDV(
                  pIDCOLUMNNAME: model.eSERVICESVS![popipIndex].iDCOLUMNNAME,
                  pRETURNMSG: "null",
                  pRETURNSTATUS: getCCPDFFStructureModelList![popipIndex].dEFAULTVALUE,
                  pVALUECOLUMNNAME: model.eSERVICESVS![popipIndex].vALUECOLUMNNAME);
              getCCPDFFStructureModelList![index].eSERVICESDV = eservicesdv;
              setState(() {});
              if (model.cHILDSEGMENTSDVSplited?.isNotEmpty ?? false) {
                // getDefaultValues(model);
              }
            });
      }

      return DynamicTextFieldWidget(
        (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
        model.eSERVICESDV?.pIDCOLUMNNAME ?? "",
        isReadOnly: model.rEADONLY == "Y",
        onChange: (text) {
          model.fieldAnswer = text;
        },
      ).paddingOnly(bottom: 12);
    } else if (model.fORMATTYPE == "X" || model.fORMATTYPE == "Y") {
      String displayText = model.eSERVICESDV?.pIDCOLUMNNAME ?? (getCCPDFFStructureModelList![index].fieldAnswer ?? "");
      if (getCCPDFFStructureModelList![index].isDefaultTypeIsCDPS) {
        if (displayText.contains(" 00:00:00")) {
          displayText = displayText.replaceAll(" 00:00:00", "");
        }
        if (!displayText.contains("-")) {
          displayText = DateFormat('yyyy-MM-dd').format(DateFormat("yyyy/MM/dd").parse(displayText));
        }
      }
      return DynamicTextFieldWidget(
        (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
        displayText.isEmpty ? LocaleKeys.pleaseSelectDate.tr() : displayText,
        suffixIconData: Icons.calendar_today,
        isEnable: false,
        onTap: () async {
          if ((getCCPDFFStructureModelList![index].eSERVICESDV?.pVALUECOLUMNNAME != null)) {
            if (getCCPDFFStructureModelList![index].isDefaultTypeIsCDPS) {
              selectedDate = DateFormat("yyyy/MM/dd").parse(getCCPDFFStructureModelList![index].eSERVICESDV!.pVALUECOLUMNNAME!.replaceAll('/"', '').replaceAll(" 00:00:00", ""));
            } else {
              selectedDate = DateTime.parse(getCCPDFFStructureModelList![index].eSERVICESDV!.pVALUECOLUMNNAME!);
            }
          }
          DateTime date = await _selectDate(context);
          DateTime date1 = DateTime(date.year, date.month, date.day);
          getCCPDFFStructureModelList![index].fieldAnswer = date.toString();
          ESERVICESDV eservicesdv = ESERVICESDV(
              pIDCOLUMNNAME: DateFormat('yyyy-MM-dd').format(date1),
              pRETURNMSG: "null",
              pRETURNSTATUS: getCCPDFFStructureModelList![index].dEFAULTVALUE,
              pVALUECOLUMNNAME: getCCPDFFStructureModelList![index].isDefaultTypeIsCDPS ? DateFormat('yyyy-MM-dd hh:mm:ss').format(date) : DateFormat('yyyy-MM-ddThh:mm:ss.s').format(date));
          getCCPDFFStructureModelList![index].eSERVICESDV = eservicesdv;
          setState(() {});
          if (model.cHILDSEGMENTSDVSplited?.isNotEmpty ?? false) {
            // calGetValueSetValues(model);
          }
        },
      ).paddingOnly(bottom: 12);
    } else if (model.fORMATTYPE == "I") {
      return DynamicTextFieldWidget(
        (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
        model.eSERVICESDV?.pIDCOLUMNNAME ?? (getCCPDFFStructureModelList![index].fieldAnswer ?? ""),
        suffixIconData: Icons.access_time_filled_rounded,
        isEnable: false,
        onTap: () async {
          if ((getCCPDFFStructureModelList![index].eSERVICESDV?.pVALUECOLUMNNAME != null)) {
            var timeString = getCCPDFFStructureModelList![index].eSERVICESDV!.pVALUECOLUMNNAME!.split(":");
            selectedDate = DateTime(0, 0, 0, int.parse(timeString[0]), int.parse(timeString[1]));

            //DateTime.parse(getEitDffStructureList![index].eSERVICESDV!.pVALUECOLUMNNAME!);
          }
          // TimeOfDay _time = await _selectTime(context);
          // DateTime tempTime = DateTime(0, 1, 1, _time.hour, _time.minute);
          // String time = DateFormat('HH:mm').format(tempTime).trim();

          // DateTime date1 = DateTime(date.year, date.month, date.day);
          //  getEitDffStructureList![index].fieldAnswer = date.toString();
          // ESERVICESDV eservicesdv = ESERVICESDV(pIDCOLUMNNAME: time, pRETURNMSG: "null", pRETURNSTATUS: getEitDffStructureList![index].dEFAULTVALUE, pVALUECOLUMNNAME: time);
          // getCCPDFFStructureModelList![index].eSERVICESDV = eservicesdv;
          setState(() {});
          if (model.cHILDSEGMENTSDVSplited?.isNotEmpty ?? false) {
            // getCCPDFFStructureModelList(model);
          }
        },
      ).paddingOnly(bottom: 12);
    }

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

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