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/colors.dart';
import 'package:mohem_flutter_app/classes/date_uitl.dart';
import 'package:mohem_flutter_app/classes/file_process.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/my_requests/get_ccp_output_model.dart';
import 'package:mohem_flutter_app/models/my_requests/get_ccp_transactions_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 MyRequests extends StatefulWidget {
  const MyRequests({Key? key}) : super(key: key);

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

class _MyRequestsState extends State<MyRequests> {
  List<GetConcurrentProgramsModel> getConcurrentProgramsList = [];
  GetConcurrentProgramsModel? selectedConcurrentProgramList;

  List<GetCCPTransactionsModel> getCCPTransactionsList = [];

  bool isNewRequest = false;

  @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(
            physics: const BouncingScrollPhysics(),
            children: [
              Container(
                padding: const EdgeInsets.only(left: 12, right: 12, top: 10, bottom: 0),
                margin: const EdgeInsets.only(left: 12, right: 12, top: 0, bottom: 0),
                child: 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];
                      getCCPTransactions(selectedConcurrentProgramList?.cONCURRENTPROGRAMNAME);
                      setState(() {});
                    }),
              ),
              12.height,
              Expanded(
                // todo list don't have data, need to confirm later , because have issues, need fixes

                child: ListView.separated(
                    physics: const BouncingScrollPhysics(),
                    shrinkWrap: true,
                    itemBuilder: (BuildContext context, int index) {
                      return Container(
                        width: double.infinity,
                        padding: const EdgeInsets.only(left: 12, right: 12, top: 10, bottom: 12),
                        margin: const EdgeInsets.only(left: 12, right: 12, top: 10, bottom: 0),
                        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(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                ("Request ID: " + getCCPTransactionsList[index].rEQUESTID.toString()).toText12(color: MyColors.grey57Color),
                                DateUtil.formatDateToDate(DateUtil.convertStringToDate(getCCPTransactionsList[index].rEQUESTDATE!), false).toText12(color: MyColors.grey70Color),
                              ],
                            ),
                            Container(
                              padding: const EdgeInsets.only(top: 10.0),
                              child: ("Phase: " + getCCPTransactionsList[index].cCPPHASE!).toText12(color: MyColors.grey57Color, isBold: true),
                            ),
                            Container(
                              padding: const EdgeInsets.only(top: 10.0),
                              child: "Program Name: ".toText12(color: MyColors.grey57Color, isBold: true),
                            ),
                            getCCPTransactionsList[index].cONCURRENTPROGRAMNAME!.toText12(color: MyColors.gradiantEndColor),
                            Container(
                              padding: const EdgeInsets.only(top: 10.0),
                              child: InkWell(
                                onTap: () {
                                  getCCPOutput(getCCPTransactionsList[index].rEQUESTID.toString());
                                },
                                child: Row(
                                  children: [
                                    "Output: ".toText12(color: MyColors.grey57Color),
                                    8.width,
                                    "Open PDF".toText12(color: MyColors.grey57Color),
                                    6.width,
                                    const Icon(Icons.launch, size: 16.0),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      );
                    },
                    separatorBuilder: (BuildContext context, int index) => 12.height,
                    itemCount: getCCPTransactionsList.length),
              ),
            ],
          ).expanded,
          1.divider,
          DefaultButton(LocaleKeys.createRequest.tr(), () async {
            openNewRequest();
          }).insideContainer,
        ],
      ),
    );
  }

  void openNewRequest() async {
    await Navigator.pushNamed(context, AppRoutes.newRequest).then((value) {
      // getOpenTickets();
    });
  }

  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 getCCPTransactions(String? templateName) async {
    try {
      Utils.showLoading(context);
      getCCPTransactionsList = await MyRequestsApiClient().getCCPTransactions(templateName);
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getCCPOutput(String requestID) async {
    GetCCPOutputModel getCCPOutputModel;
    try {
      Utils.showLoading(context);
      getCCPOutputModel = await MyRequestsApiClient().getCCPOutput(requestID);
      Utils.hideLoading(context);
      await FileProcess.downloadFile(getCCPOutputModel.pOUTPUTFILE!, requestID).then((value) {
        File file = value;
        debugPrint(file.toString());
        FileProcess.openFile(requestID);
      });
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }
}
