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/colors.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: "Pending Transactions",
        ),
        body: SingleChildScrollView(
          child: Container(
            width: double.infinity,
            padding: const EdgeInsets.only(left: 12, right: 12, top: 10, bottom: 10),
            margin: const EdgeInsets.only(left: 12, right: 12, top: 10, bottom: 10),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
              boxShadow: [
                BoxShadow(
                  color: const Color(0xff000000).withOpacity(.05),
                  blurRadius: 26,
                  offset: const Offset(0, -3),
                ),
              ],
            ),
            child: Column(
              children: [
                12.height,
                PopupMenuButton(
                    child: DynamicTextFieldWidget(
                      "Please select request type",
                      selectedFunction?.fUNCTIONPROMPT ?? "",
                      isEnable: false,
                      isPopup: true,
                      isInputTypeNum: true,
                      isReadOnly: false,
                    ).paddingOnly(bottom: 12),
                    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(
                  "Date From: ",
                  selectedDateFrom.toString().split(" ")[0],
                  suffixIconData: Icons.calendar_today,
                  isEnable: false,
                  onTap: () async {
                    selectedDateFrom = await _selectDate(context, DateTime.now());
                    setState(() {});
                  },
                ).paddingOnly(bottom: 12),
                12.height,
                DynamicTextFieldWidget(
                  "Date To: ",
                  selectedDateTo.toString().split(" ")[0],
                  suffixIconData: Icons.calendar_today,
                  isEnable: false,
                  onTap: () async {
                    selectedDateTo = await _selectDate(context, DateTime.now());
                    setState(() {});
                  },
                ).paddingOnly(bottom: 12),
              ],
            ),
          ),
        ),
        bottomSheet: Container(
          decoration: const BoxDecoration(
            color: MyColors.white,
            boxShadow: [
              BoxShadow(color: MyColors.lightGreyEFColor, spreadRadius: 3),
            ],
          ),
          child: DefaultButton(
                  LocaleKeys.submit.tr(),
                  selectedFunction == null
                      ? null
                      : () async {
                          openRequestDetails();
                        })
              .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 {
      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;
  }

  void getRequestTypes() async {
    try {
      Utils.showLoading(context);
      getPendingTransactionsFunctions = await PendingTransactionsApiClient().getPendingReqFunctions();
      Utils.hideLoading(context);
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void openRequestDetails() async {
    await Navigator.pushNamed(context, AppRoutes.pendingTransactionsDetails,
        arguments: {"selectedFunctionID": selectedFunction?.fUNCTIONID, "dateFrom": DateUtil.convertDateToString(selectedDateFrom), "dateTo": DateUtil.convertDateToString(selectedDateTo)});
  }

  void getPendingReqDetails() async {
    try {
      Utils.showLoading(context);
      getPendingTransactionsFunctions = await PendingTransactionsApiClient().getPendingReqFunctions();
      Utils.hideLoading(context);
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }
}
