import 'package:diplomaticquarterapp/core/model/labs/lab_result.dart';
import 'package:diplomaticquarterapp/core/model/labs/patient_lab_orders.dart';
import 'package:diplomaticquarterapp/core/service/medical/labs_service.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/pages/medical/labs/passport_update_page.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart';
import 'package:diplomaticquarterapp/uitl/utils_new.dart';
import 'package:diplomaticquarterapp/widgets/buttons/custom_text_button.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/confirm_send_email_dialog.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'FlowChartPage.dart';

class LabResultWidget extends StatelessWidget {
  final String filterName;
  final List<LabResult> patientLabResultList;
  final PatientLabOrders patientLabOrder;

  LabResult covidLabResult;

  LabResultWidget({Key key, this.filterName, this.patientLabResultList, this.patientLabOrder}) : super(key: key);
  ProjectViewModel projectViewModel;

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);

    return Container(
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 8),
          Row(
            //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                filterName,
                style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Color(0xff2E303A), letterSpacing: -0.56, height: 21 / 14),
              ),
              SizedBox(width: 16),
            ],
          ),
          Table(
            columnWidths: {
              0: FlexColumnWidth(2),
              1: FlexColumnWidth(1.5),
              2: FlexColumnWidth(1),
              3: FlexColumnWidth(1.7),
            },
            children: fullData(patientLabResultList, context),
          ),
          checkIfCovidLab(patientLabResultList)
              ? Container(
                  margin: EdgeInsets.only(top: 10.0),
                  child: ButtonTheme(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10.0),
                    ),
                    minWidth: MediaQuery.of(context).size.width * 0.91,
                    height: 45.0,
                    child: CustomTextButton(
                      backgroundColor: Color(0xFFc5272d),
                      disabledForegroundColor: Colors.red[300].withOpacity(0.38),
                      disabledBackgroundColor: Colors.red[300].withOpacity(0.12),
                      elevation: 0,
                      onPressed: () {
                        showKSADialog(context);
                      },
                      child: Text(TranslationBase.of(context).generateCovidCertificate, style: TextStyle(fontSize: 18.0, color: Colors.white)),
                    ),
                  ),
                )
              : Container(),
          Padding(
            padding: const EdgeInsets.only(top: 12.0),
            child: Divider(
              height: 1,
              color: Color(0xff2E303A),
              thickness: 1,
            ),
          ),
        ],
      ),
    );
  }

  generateCovidCertificate(BuildContext context, String isOutsideKSA) {
    LabsService service = new LabsService();
    GifLoaderDialogUtils.showMyDialog(context);

    service.generateCovidLabReport(covidLabResult, isOutsideKSA).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showSuccessToast(message: TranslationBase.of(context).emailSentSuccessfully);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }

  openPassportUpdatePage(BuildContext context) {
    Navigator.push(context, FadePage(page: PassportUpdatePage())).then((value) {
      print(value);
      if (value != null && value == true) {
        showConfirmMessage(context, projectViewModel.user.emailAddress, "yes");
      }
    });
  }

  void showKSADialog(BuildContext context) {
    ConfirmDialog dialog = new ConfirmDialog(
        context: context,
        confirmMessage: TranslationBase.of(context).isReportOutsideKsa,
        okText: TranslationBase.of(context).yes,
        cancelText: TranslationBase.of(context).no,
        okFunction: () => {
              Navigator.of(context).pop(),
              openPassportUpdatePage(context)
              // showConfirmMessage(context, projectViewModel.user.emailAddress, "yes")
            },
        cancelFunction: () => {showConfirmMessage(context, projectViewModel.user.emailAddress, "no")});
    dialog.showAlertDialog(context);
  }

  void showConfirmMessage(BuildContext context, String email, String isOutsideKSA) {
    showDialog(
      context: context,
      builder: (cxt) => ConfirmSendEmailDialog(
        email: email,
        onTapSendEmail: () {
          generateCovidCertificate(context, isOutsideKSA);
        },
      ),
    );
  }

  bool checkIfCovidLab(List<LabResult> labResultList) {
    bool isCovidResult = false;
    labResultList.forEach((order) {
      if ((order.testCode.toUpperCase().contains("COVID") || order.testCode.toUpperCase().contains("COV")) && order.isCertificateAllowed.toString().toLowerCase() == "true") {
        isCovidResult = true;
        covidLabResult = order;
      }
    });

    return isCovidResult;
  }

  List<TableRow> fullData(List<LabResult> labResultList, context) {
    List<TableRow> tableRow = [];
    tableRow.add(
      TableRow(
        children: [
          Utils.tableColumnTitle(TranslationBase.of(context).description, showDivider: false),
          Utils.tableColumnTitle(TranslationBase.of(context).value, showDivider: false),
          Utils.tableColumnTitle(TranslationBase.of(context).range, showDivider: false),
          Utils.tableColumnTitle("", showDivider: false),
        ],
      ),
    );

    for (int i = 0; i < labResultList.length; i++) {
      tableRow.add(
        TableRow(
          children: [
            mHeight(8),
            mHeight(8),
            mHeight(8),
            mHeight(8),
          ],
        ),
      );
      tableRow.add(
        TableRow(
          decoration: containerColorRadiusBorderWidth(Colors.grey[100], 12, Colors.grey[300], 0.6),
          children: [
            Padding(
              padding: EdgeInsets.only(left: projectViewModel.isArabic ? 0 : 12, right: projectViewModel.isArabic ? 12 : 0),
              child: Utils.tableColumnValue(labResultList[i].description ?? "", isLast: true, mProjectViewModel: projectViewModel),
            ),
            Utils.tableColumnValue(labResultList[i].resultValue + " " + labResultList[i].uOM, isLast: true, mProjectViewModel: projectViewModel),
            Utils.tableColumnValue(labResultList[i].referanceRange, isLast: true, isCapitable: false, mProjectViewModel: projectViewModel),
            !checkIfCovidLab(patientLabResultList)
                ? InkWell(
                    onTap: () {
                      Navigator.push(
                        context,
                        FadePage(
                          page: FlowChartPage(
                            filterName: filterName,
                            patientLabOrder: patientLabOrder,
                          ),
                        ),
                      );
                    },
                    child: Padding(
                      padding: EdgeInsets.only(left: !projectViewModel.isArabic ? 0 : 12, right: !projectViewModel.isArabic ? 12 : 0),
                      child: Utils.tableColumnValueWithUnderLine(TranslationBase.of(context).viewFlowChart, isLast: true, isCapitable: false),
                    ),
                  )
                : Container(),
          ],
        ),
      );
    }
    return tableRow;
  }
}
