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/pending_transactions_api_client.dart';
import 'package:mohem_flutter_app/classes/date_uitl.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/pending_transactions/get_req_functions.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 PendingTransactions extends StatefulWidget {
  const PendingTransactions({Key? key}) : super(key: key);

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

class _PendingTransactionsState extends State<PendingTransactions> {
  List<GetPendingTransactionsFunctions> getPendingTransactionsFunctions = [];
  GetPendingTransactionsFunctions? selectedFunction;

  DateTime selectedDateFrom = DateTime.now();
  DateTime selectedDateTo = DateTime.now();

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBarWidget(
        context,
        title: LocaleKeys.pendingTransactions.tr(),
      ),
      body: Column(
        children: [
          ListView(
            padding: const EdgeInsets.all(21),
            children: [
              PopupMenuButton(
                  child: DynamicTextFieldWidget(
                    LocaleKeys.requestType.tr(),
                    selectedFunction?.fUNCTIONPROMPT ?? LocaleKeys.selectRequestType.tr(),
                    isEnable: false,
                    isPopup: true,
                    isInputTypeNum: true,
                    isReadOnly: false,
                  ),
                  itemBuilder: (_) => <PopupMenuItem<int>>[
                        for (int i = 0; i < getPendingTransactionsFunctions.length; i++) PopupMenuItem<int>(child: Text(getPendingTransactionsFunctions![i].fUNCTIONPROMPT!), value: i),
                      ],
                  onSelected: (int popupIndex) {
                    selectedFunction = getPendingTransactionsFunctions[popupIndex];
                    setState(() {});
                  }),
              12.height,
              DynamicTextFieldWidget(
                LocaleKeys.dateFrom.tr(),
                selectedDateFrom.toString().split(" ")[0],
                suffixIconData: Icons.calendar_today,
                isEnable: false,
                onTap: () async {
                  selectedDateFrom = await _selectDate(context, DateTime.now());
                  setState(() {});
                },
              ),
              12.height,
              DynamicTextFieldWidget(
                LocaleKeys.dateTo.tr(),
                selectedDateTo.toString().split(" ")[0],
                suffixIconData: Icons.calendar_today,
                isEnable: false,
                onTap: () async {
                  selectedDateTo = await _selectDate(context, DateTime.now());
                  setState(() {});
                },
              )
            ],
          ).expanded,
          DefaultButton(
                  LocaleKeys.submit.tr(),
                  selectedFunction == null
                      ? null
                      : () async {
                          Navigator.pushNamed(
                            context,
                            AppRoutes.pendingTransactionsDetails,
                            arguments: {
                              "selectedFunctionID": selectedFunction?.fUNCTIONID,
                              "dateFrom": DateUtil.convertDateToString(selectedDateFrom),
                              "dateTo": DateUtil.convertDateToString(selectedDateTo)
                            },
                          );
                        })
              .insideContainer
        ],
      ),
    );
  }

  Future<DateTime> _selectDate(BuildContext context, DateTime selectedDate) 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 getRequestTypes() async {
    try {
      Utils.showLoading(context);
      getPendingTransactionsFunctions = await PendingTransactionsApiClient().getPendingReqFunctions();
      Utils.hideLoading(context);
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }
}
