import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/Appointments/DoctorListResponse.dart';
import 'package:diplomaticquarterapp/models/MyInvoices/DentalInvoiceDetailResponse.dart';
import 'package:diplomaticquarterapp/models/MyInvoices/GetDentalAppointmentsResponse.dart';
import 'package:diplomaticquarterapp/models/header_model.dart';
import 'package:diplomaticquarterapp/services/my_invoice_service/my_invoice_services.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/date_uitl.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/my_rich_text.dart';
import 'package:diplomaticquarterapp/widgets/new_design/doctor_header.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class InvoiceDetail extends StatefulWidget {
  final DoctorList doctor;
  final ListDentalAppointments listDentalAppointments;
  final DentalInvoiceDetailResponse dentalInvoiceDetailResponse;
  final BuildContext context;

  InvoiceDetail(this.doctor, this.listDentalAppointments, this.dentalInvoiceDetailResponse, this.context);

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

class _InvoiceDetailState extends State<InvoiceDetail> {
  dynamic totalServiceRate = 0;

  dynamic totalDiscount = 0;

  dynamic totalVAT = 0;

  dynamic subTotal = 0;

  dynamic grandTotal = 0;

  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectViewModel = Provider.of(context);
    generateInvoiceDetails();
    return AppScaffold(
        appBarTitle: widget.doctor.doctorTitle != null ? widget.doctor.doctorTitle.toString() : TranslationBase.of(context).dr + " " + widget.doctor.name.toString(),
        isShowAppBar: true,
        isShowDecPage: false,
        showNewAppBar: true,
        showNewAppBarTitle: true,
        body: SingleChildScrollView(
          child: Container(
            child: Column(
              children: [
                // DoctorView(doctor: doctor, isLiveCareAppointment: false, isShowFlag: false),
                DoctorHeader(
                  headerModel: HeaderModel(
                      widget.doctor.name,
                      widget.doctor.doctorID,
                      widget.doctor.doctorImageURL,
                      widget.doctor.speciality,
                      widget.doctor.clinicName,
                      widget.doctor.projectName,
                      DateUtil.convertStringToDate(widget.doctor.date),
                      null,
                      widget.doctor.nationalityFlagURL,
                      widget.doctor.doctorRate,
                      widget.doctor.actualDoctorRate,
                      widget.doctor.noOfPatientsRate ?? 0,
                      projectViewModel.user.emailAddress,
                      decimalDoctorRate: widget.doctor.decimalDoctorRate.toString()),
                  onTap: () {
                    sendInvoiceEmail();
                  },
                ),
                Container(
                  child: Container(
                    decoration: cardRadius(12),
                    margin: EdgeInsets.only(left: 16, top: 8, right: 16, bottom: 16),
                    child: Padding(
                      padding: const EdgeInsets.all(12.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Table(
                            columnWidths: {
                              0: FlexColumnWidth(2.0),
                              1: FlexColumnWidth(1.5),
                              2: FlexColumnWidth(1.5),
                              3: FlexColumnWidth(1.5),
                            },
                            children: fullData(context),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                Container(
                  width: double.infinity,
                  child: Container(
                    decoration: cardRadius(12),
                    margin: EdgeInsets.only(left: 16, top: 8, right: 16, bottom: 16),
                    child: Padding(
                      padding: const EdgeInsets.all(15.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Container(
                            margin: EdgeInsets.only(bottom: 10.0),
                            child: Text(TranslationBase.of(context).cardDetail, style: TextStyle(color: Colors.black, letterSpacing: -0.64, fontSize: 18.0, fontWeight: FontWeight.bold)),
                          ),
                          MyRichText(
                              TranslationBase.of(context).insuranceCompany + ": ",
                              projectViewModel.isArabic
                                  ? widget.dentalInvoiceDetailResponse.listEInvoiceForDental[0].groupNameN
                                  : widget.dentalInvoiceDetailResponse.listEInvoiceForDental[0].companyName,
                              projectViewModel.isArabic),
                          MyRichText(
                              TranslationBase.of(context).insuranceID + ": ",
                              widget.dentalInvoiceDetailResponse.listEInvoiceForDental[0].insuranceID != null ? widget.dentalInvoiceDetailResponse.listEInvoiceForDental[0].insuranceID : "N/A",
                              projectViewModel.isArabic),
                        ],
                      ),
                    ),
                  ),
                ),
                Container(
                    width: double.infinity,
                    child: Container(
                      decoration: cardRadius(12),
                      margin: EdgeInsets.only(left: 16, top: 8, right: 16, bottom: 16),
                      child: Padding(
                        padding: const EdgeInsets.all(15.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Container(
                              margin: EdgeInsets.only(bottom: 10.0),
                              child: Text(TranslationBase.of(context).totalBalance, style: TextStyle(letterSpacing: -0.64, color: Colors.black, fontSize: 18.0, fontWeight: FontWeight.bold)),
                            ),
                            Container(
                              width: double.infinity,
                              padding: EdgeInsets.only(top: 10, bottom: 5),
                              child: Row(
                                children: [
                                  Expanded(
                                    child: _getNormalText(TranslationBase.of(context).discount),
                                  ),
                                  Expanded(
                                    child: _getNormalText(this.totalDiscount.toString() + " " + TranslationBase.of(context).sar, isBold: true),
                                  )
                                ],
                              ),
                            ),
                            mDivider( Color(0xffEFEFEF),),
                            Container(
                              width: double.infinity,
                              padding: EdgeInsets.only(top: 10, bottom: 5),
                              child: Row(
                                children: [
                                  Expanded(
                                    child: _getNormalText(TranslationBase.of(context).totalVAT.toString() +
                                        " (" +
                                        widget.dentalInvoiceDetailResponse.listEInvoiceForDental[0].listConsultation[0].vATPercentage.toString() +
                                        "%): "),
                                  ),
                                  Expanded(
                                    child: _getNormalText(num.tryParse(this.totalVAT.toString()).toStringAsFixed(2) + " " + TranslationBase.of(context).sar, isBold: true),
                                  )
                                ],
                              ),
                            ),
                            mDivider( Color(0xffEFEFEF),),
                            Container(
                              width: double.infinity,
                              padding: EdgeInsets.only(top: 10, bottom: 5),
                              child: Row(
                                children: [
                                  Expanded(
                                    child: _getNormalText(TranslationBase.of(context).total),
                                  ),
                                  Expanded(
                                    child: _getNormalText(this.subTotal.toString() + " " + TranslationBase.of(context).sar, isBold: true),
                                  )
                                ],
                              ),
                            ),
                            mDivider( Color(0xffEFEFEF),),
                            Container(
                              width: double.infinity,
                              padding: EdgeInsets.only(top: 10, bottom: 5),
                              child: Row(
                                children: [
                                  Expanded(
                                    child: _getNormalText(TranslationBase.of(context).paid),
                                  ),
                                  Expanded(
                                    child: _getNormalText(this.grandTotal.toString() + " " + TranslationBase.of(context).sar, isBold: true),
                                  )
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    )),
                SizedBox(
                  height: 100.0,
                ),
              ],
            ),
          ),
        ));
  }

  void generateInvoiceDetails() {
    totalServiceRate = 0;
    totalDiscount = 0;
    totalVAT = 0;
    subTotal = 0;
    grandTotal = 0;

    List<ListConsultation> listConsultations = new List();

    widget.dentalInvoiceDetailResponse.listEInvoiceForDental[0].listConsultation.forEach((item) {
      var i = listConsultations.indexWhere((x) => x.procedureID == item.procedureID);
      if (i <= -1) {
        listConsultations.add(item);
      }
    });

    listConsultations.forEach((element) {
      print(element.procedureID);
      this.totalServiceRate += element.total;
      this.totalDiscount += element.discountAmount;
      this.totalVAT += element.totalVATAmount;
    });

    this.subTotal = this.totalServiceRate - this.totalDiscount;
    this.grandTotal = this.subTotal + this.totalVAT;
  }

  sendInvoiceEmail() {
    GifLoaderDialogUtils.showMyDialog(widget.context);
    MyInvoicesService myInvoicesService = new MyInvoicesService();

    myInvoicesService.sendDentalAppointmentInvoiceEmail(widget.listDentalAppointments.projectID, widget.listDentalAppointments.appointmentNo, widget.context).then((res) {
      GifLoaderDialogUtils.hideDialog(widget.context);
      if (res['MessageStatus'] == 1) {
        AppToast.showSuccessToast(message: TranslationBase.of(widget.context).emailSentSuccessfully);
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(widget.context);
      print(err);
      AppToast.showErrorToast(message: err);
      Navigator.of(widget.context).pop();
    });
  }

  List<TableRow> fullData(context) {
    List<TableRow> tableRow = [];

    tableRow.add(
      TableRow(
        children: [
          Utils.tableColumnTitle(TranslationBase.of(context).description),
          Utils.tableColumnTitle(TranslationBase.of(context).quantity),
          Utils.tableColumnTitle(TranslationBase.of(context).price),
          Utils.tableColumnTitle(TranslationBase.of(context).total),
        ],
      ),
    );
    for (int i = 0; i < widget.dentalInvoiceDetailResponse.listEInvoiceForDental[0].listConsultation.length; i++) {
      tableRow.add(
        TableRow(children: [
          Utils.tableColumnValue('${widget.dentalInvoiceDetailResponse.listEInvoiceForDental[0].listConsultation[i].procedureName}',
              isLast: i == (widget.dentalInvoiceDetailResponse.listEInvoiceForDental[0].listConsultation.length - 1)),
          Utils.tableColumnValue('${widget.dentalInvoiceDetailResponse.listEInvoiceForDental[0].listConsultation[i].quantity}',
              isLast: i == (widget.dentalInvoiceDetailResponse.listEInvoiceForDental[0].listConsultation.length - 1)),
          Utils.tableColumnValue('${widget.dentalInvoiceDetailResponse.listEInvoiceForDental[0].listConsultation[i].price.toString() + " " + TranslationBase.of(context).sar}',
              isLast: i == (widget.dentalInvoiceDetailResponse.listEInvoiceForDental[0].listConsultation.length - 1)),
          Utils.tableColumnValue('${widget.dentalInvoiceDetailResponse.listEInvoiceForDental[0].listConsultation[i].total.toString() + " " + TranslationBase.of(context).sar}',
              isLast: i == (widget.dentalInvoiceDetailResponse.listEInvoiceForDental[0].listConsultation.length - 1)),
        ]),
      );
    }
    return tableRow;
  }

  _getNormalText(text, {bool isBold = false}) {
    return Text(
      text,
      style: TextStyle(
        fontSize: isBold ? 14 : 12,
        letterSpacing: -0.5,
        color: isBold ? Colors.black : Colors.grey[700],
        fontWeight: FontWeight.w600,
      ),
    );
  }
}
