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/classes/utils.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/generic_response_model.dart';
import 'package:mohem_flutter_app/models/get_eit_dff_structure_list_model.dart';
import 'package:mohem_flutter_app/ui/my_attendance/dynamic_screens/dynamic_listview_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 DynamicInputScreen extends StatefulWidget {
  DynamicInputScreen({Key? key}) : super(key: key);

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

class _DynamicInputScreenState extends State<DynamicInputScreen> {
  GenericResponseModel? genericResponseModel;
  List<GetEITDFFStructureList>? getEitDffStructureList;
  DynamicListViewParams? dynamicParams;

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

  void getTransactionsStructure() async {
    try {
      Utils.showLoading(context);
      genericResponseModel = await MyAttendanceApiClient().getEitDffStructure(dynamicParams!.dynamicId);
      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);
    }
  }

  void calGetValueSetValues(GetEITDFFStructureList structureList) async {
    try {
      Utils.showLoading(context);
      String segmentId = structureList.cHILDSEGMENTSVS!;
      List<GetEITDFFStructureList> filteredList = getEitDffStructureList?.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();
      ESERVICESVS genericResponseModel = await MyAttendanceApiClient().getValueSetValues(structureList.cHILDSEGMENTSVS!, structureList.dESCFLEXCONTEXTCODE!, structureList.dESCFLEXNAME!, values);

      int index = getEitDffStructureList!.indexWhere((element) => element.sEGMENTNAME == structureList.cHILDSEGMENTSVS);
      getEitDffStructureList![index].eSERVICESVS!.add(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 DynamicListViewParams;
      getTransactionsStructure();
    }
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBarWidget(
        context,
        title: dynamicParams!.title,
      ),
      body: Column(
        children: [
          (getEitDffStructureList == null
                  ? const SizedBox()
                  : (getEitDffStructureList!.isEmpty
                      ? LocaleKeys.noDataAvailable.tr().toText16().center
                      : ListView.separated(
                          physics: const BouncingScrollPhysics(),
                          padding: const EdgeInsets.all(21),
                          itemBuilder: (cxt, int parentIndex) => parseDynamicFormatType(getEitDffStructureList![parentIndex], parentIndex),
                          separatorBuilder: (cxt, index) => 0.height,
                          itemCount: getEitDffStructureList!.length)))
              .expanded,
          // 12.height,
          DefaultButton(
            LocaleKeys.next.tr(),
            (getEitDffStructureList ?? []).isEmpty
                ? null
                : () => {
                      //Navigator.of(context).pushNamed(LOGIN_TYPE)
                    },
          ).insideContainer,
        ],
      ),
    );
  }

  Widget parseDynamicFormatType(GetEITDFFStructureList 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.eSERVICESDV?.pIDCOLUMNNAME ?? "",
              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 index) {
              ESERVICESDV eservicesdv = ESERVICESDV(
                  pIDCOLUMNNAME: model.eSERVICESVS![index].vALUECOLUMNNAME,
                  pRETURNMSG: "null",
                  pRETURNSTATUS: getEitDffStructureList![index].dEFAULTVALUE,
                  pVALUECOLUMNNAME: model.eSERVICESVS![index].vALUECOLUMNNAME);

              print(model.eSERVICESVS![index].toJson());
            });
      }

      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") {
      return DynamicTextFieldWidget(
        (model.sEGMENTPROMPT ?? "") + (model.rEQUIREDFLAG == "Y" ? "*" : ""),
        model.eSERVICESDV?.pIDCOLUMNNAME ?? (getEitDffStructureList![index].fieldAnswer ?? ""),
        suffixIconData: Icons.calendar_today,
        isEnable: false,
        onTap: () async {
          DateTime date = await _selectDate(context);
          DateTime date1 = DateTime(date.year, date.month, date.day);
          getEitDffStructureList![index].fieldAnswer = date.toString();
          ESERVICESDV eservicesdv = ESERVICESDV(
              pIDCOLUMNNAME: DateFormat('yyyy-MM-dd').format(date1),
              pRETURNMSG: "null",
              pRETURNSTATUS: getEitDffStructureList![index].dEFAULTVALUE,
              pVALUECOLUMNNAME: DateFormat('yyyy-MM-ddThh:mm:ss.s').format(date));
          getEitDffStructureList![index].eSERVICESDV = eservicesdv;
          setState(() {});
          if (model.cHILDSEGMENTSDVSplited?.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 {
      final 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;
  }
}
