import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:hmg_patient_app/config/config.dart';
import 'package:hmg_patient_app/core/model/reports/Reports.dart';
import 'package:hmg_patient_app/core/service/medical/reports_service.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/locator.dart';
import 'package:hmg_patient_app/main.dart';
import 'package:hmg_patient_app/theme/colors.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/date_uitl.dart';
import 'package:hmg_patient_app/uitl/gif_loader_dialog_utils.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/uitl/utils.dart';
import 'package:hmg_patient_app/uitl/utils_new.dart';
import 'package:hmg_patient_app/widgets/avatar/large_avatar.dart';
import 'package:hmg_patient_app/widgets/dialogs/confirm_send_email_dialog.dart';
import 'package:hmg_patient_app/widgets/my_rich_text.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:open_filex/open_filex.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'package:share_plus/share_plus.dart';

class ReportListWidget extends StatelessWidget {
  final List<Reports> reportList;
  final String? emailAddress;

  ReportListWidget({required this.reportList, this.emailAddress});

  late ProjectViewModel projectViewModel;

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    return reportList.length > 0
        ? ListView.separated(
            physics: BouncingScrollPhysics(),
            padding: EdgeInsets.only(bottom: 14, top: 14, left: 21, right: 21),
            separatorBuilder: (context, index) => SizedBox(height: 14),
            itemBuilder: (context, index) {
              Reports report = reportList[index];
              return Container(
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(
                      Radius.circular(10.0),
                    ),
                    boxShadow: [
                      BoxShadow(
                        color: Color(0xff000000).withOpacity(.05),
                        //spreadRadius: 5,
                        blurRadius: 27,
                        offset: Offset(0, -3),
                      ),
                    ],
                    color: Colors.white),
                child: Padding(
                  padding: const EdgeInsets.only(left: 12, right: 12, top: 12, bottom: 12),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      if (report.doctorName != null)
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              report.doctorName,
                              style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Color(0xff2E303A), letterSpacing: -0.64, height: 25 / 16),
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: [
                                Text(DateUtil.getDayMonthYearDateFormatted(report.requestDate!),
                                    style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Color(0xff2B353E), letterSpacing: -0.48, height: 18 / 12)),
                                Text(DateUtil.formatDateToTimeLang(report.requestDate!, projectViewModel.isArabic),
                                    style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Color(0xff2B353E), letterSpacing: -0.48, height: 18 / 12)),
                              ],
                            ),
                          ],
                        ),
                      if (report.doctorName != null) SizedBox(height: 6),
                      Row(
                        mainAxisSize: MainAxisSize.min,
                        children: <Widget>[
                          LargeAvatar(
                            name: report.doctorName,
                            url: report.doctorImageURL,
                            width: 48,
                            height: 48,
                          ),
                          SizedBox(width: 11),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisSize: MainAxisSize.min,
                              children: <Widget>[
                                if (report.projectName != null) MyRichText(TranslationBase.of(context).hospital + ":", report.projectName!, projectViewModel.isArabic),
                                if (report.clinicDescription != null) MyRichText(TranslationBase.of(context).clinic + ":", report.clinicDescription!, projectViewModel.isArabic),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  mainAxisSize: MainAxisSize.max,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    RatingBar(
                                      initialRating: report.actualDoctorRate == null ? 0.0 : report.actualDoctorRate!.toDouble(),
                                      itemSize: 16,
                                      ratingWidget: RatingWidget(
                                        full: Icon(
                                          Icons.star,
                                          color: CustomColors.accentColor,
                                        ),
                                        half: Icon(
                                          Icons.star_half,
                                          color: CustomColors.accentColor,
                                        ),
                                        empty: Icon(
                                          Icons.star_border,
                                          color: CustomColors.accentColor,
                                        ),
                                      ),
                                      onRatingUpdate: (double value) {},
                                      unratedColor: Colors.grey[500],
                                      updateOnDrag: false,
                                      tapOnlyMode: false,
                                    ),
                                    if (reportList[index].status == 2)
                                      Row(
                                        children: [
                                          InkWell(
                                            onTap: () {
                                              getMedicalReportPDF(report, false);
                                            },
                                            child: Padding(
                                              padding: const EdgeInsets.only(right: 11.0, left: 11.0),
                                              child: Text(TranslationBase.of(context).download,
                                                  style: TextStyle(
                                                      fontSize: 12,
                                                      fontWeight: FontWeight.w600,
                                                      fontStyle: FontStyle.italic,
                                                      color: CustomColors.accentColor,
                                                      letterSpacing: -0.48,
                                                      height: 18 / 12,
                                                      decoration: TextDecoration.underline)),
                                            ),
                                          ),
                                          InkWell(
                                            onTap: () {
                                              getMedicalReportPDF(report, true);
                                            },
                                            child: Padding(
                                              padding: const EdgeInsets.only(right: 11.0, left: 11.0),
                                              child: Text(TranslationBase.of(context).share,
                                                  style: TextStyle(
                                                      fontSize: 12,
                                                      fontWeight: FontWeight.w600,
                                                      fontStyle: FontStyle.italic,
                                                      color: CustomColors.accentColor,
                                                      letterSpacing: -0.48,
                                                      height: 18 / 12,
                                                      decoration: TextDecoration.underline)),
                                            ),
                                          ),
                                          // IconButton(
                                          //     icon: Icon(Icons.email),
                                          //     color: Color(0xff28323A),
                                          //     constraints: BoxConstraints(),
                                          //     padding: EdgeInsets.zero,
                                          //     onPressed: () {
                                          //       showConfirmMessage(reportList[index]);
                                          //     })
                                        ],
                                      ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              );
            },
            itemCount: reportList.length,
          )
        : getNoDataWidget(context);
  }

  void showConfirmMessage(Reports report) {
    showDialog(
      context: AppGlobal.context,
      builder: (cxt) => ConfirmSendEmailDialog(
        email: emailAddress,
        onTapSendEmail: () {
          sendReportEmail(report);
        },
      ),
    );
  }

  void getMedicalReportPDF(Reports report, bool isShare) {
    GifLoaderDialogUtils.showMyDialog(AppGlobal.context);
    ReportsService _reportsService = locator<ReportsService>();
    _reportsService
        .getMedicalReportPDF(
            report.projectName!,
            report.clinicDescription!,
            report.doctorName,
            DateUtil.convertDateToString(report.requestDate!),
            (Utils.isVidaPlusProject(projectViewModel, report.projectID!) ? report.invoiceNo_VP.toString() : report.invoiceNo.toString()),
            report.projectID!,
            DateUtil.convertDateToString(report.requestDate!),
            report.setupId!)
        .then((value) async {
      GifLoaderDialogUtils.hideDialog(AppGlobal.context);
      if (value["MedicalReportBase64"] != "" && value["MedicalReportBase64"] != null) {
        String path = await _createFileFromString(value["MedicalReportBase64"], "pdf");
        if (isShare) {
          Share.shareXFiles([XFile(path)], text: "Medical Report");
        } else {
          try {
            OpenFilex.open(path);
          } catch (ex) {
            AppToast.showErrorToast(message: "Cannot open file.");
          }
        }
      } else {
        AppToast.showErrorToast(message: "Cannot open file.");
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(AppGlobal.context);
      print(err);
    });
  }

  sendReportEmail(Reports report) {
    GifLoaderDialogUtils.showMyDialog(AppGlobal.context);
    ReportsService _reportsService = locator<ReportsService>();
    _reportsService
        .sendEmailForMedicalReport(
            report.projectName!,
            report.clinicDescription!,
            report.doctorName,
            DateUtil.convertDateToString(report.requestDate!),
            Utils.isVidaPlusProject(projectViewModel, report.projectID!) ? report.invoiceNo_VP.toString() : report.invoiceNo.toString(),
            report.projectID!,
            DateUtil.convertDateToString(report.requestDate!),
            report.setupId!)
        .then((value) {
      GifLoaderDialogUtils.hideDialog(AppGlobal.context);
      AppToast.showSuccessToast(message: TranslationBase.of(AppGlobal.context).emailSentSuccessfully);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(AppGlobal.context);
      print(err);
    });
  }

  Future<String> _createFileFromString(String encodedStr, String ext) async {
    Uint8List bytes = base64.decode(encodedStr);
    String dir = (await getApplicationDocumentsDirectory()).path;
    File file = File("$dir/" + DateTime.now().millisecondsSinceEpoch.toString() + "." + ext);
    await file.writeAsBytes(bytes);
    return file.path;
  }
}
