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

import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/models/Appointments/DoctorListResponse.dart';
import 'package:diplomaticquarterapp/models/Appointments/PatientShareResposne.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/routes.dart';
import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/date_uitl.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/material.dart';
import 'package:smart_progress_bar/smart_progress_bar.dart';

class QRCode extends StatefulWidget {
  PatientShareResponse patientShareResponse;
  String appoQR;
  AuthenticatedUser authUser;
  AppSharedPreferences sharedPref = AppSharedPreferences();

  QRCode({@required this.patientShareResponse, @required this.appoQR});

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

class _QRCodeState extends State<QRCode> {
  Uint8List _bytes;

  @override
  void initState() {
    // TODO: implement initState
    _bytes = base64.decode(widget.appoQR.split(',').last);
    widget.authUser = new AuthenticatedUser();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).attendRegisterCode,
      isShowAppBar: true,
      body: SingleChildScrollView(
        child: Container(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(top: 30.0),
                alignment: Alignment.center,
                child: Image.memory(_bytes, scale: 0.5),
              ),
              Container(
                margin: EdgeInsets.only(top: 20.0, left: 20.0, right: 20.0),
                child: Divider(
                  color: Colors.red[700],
                  thickness: 0.8,
                ),
              ),
              Container(
                child: Row(
                  children: <Widget>[
                    Container(
                      margin:
                          EdgeInsets.only(top: 10.0, left: 40.0, bottom: 10.0),
                      child: Image.asset(
                          "assets/images/new-design/device_icon.png",
                          width: 120.0,
                          height: 120.0),
                    ),
                    Container(
                      width: MediaQuery.of(context).size.width * 0.5,
                      margin: EdgeInsets.only(
                          top: 15.0, bottom: 10.0, left: 20.0, right: 20.0),
                      child: Text(TranslationBase.of(context).scanQRHospital,
                          style: TextStyle(
                              color: Colors.red[700],
                              fontSize: 20.0,
                              fontWeight: FontWeight.bold)),
                    ),
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 10.0, left: 20.0, right: 20.0),
                child: Divider(
                  color: Colors.red[700],
                  thickness: 0.8,
                ),
              ),
              Container(
                margin: EdgeInsets.only(
                    top: 15.0, bottom: 10.0, left: 20.0, right: 20.0),
                child: Text(TranslationBase.of(context).appoInfo,
                    style: TextStyle(
                        fontSize: 18.0,
                        color: Colors.grey[700],
                        fontWeight: FontWeight.bold)),
              ),
              Container(
                margin: EdgeInsets.only(left: 20.0, bottom: 20.0),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(10),
                  color: Colors.grey[200],
                  boxShadow: [
                    BoxShadow(color: Colors.grey, spreadRadius: 2),
                  ],
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.only(
                          top: 15.0, bottom: 10.0, left: 20.0, right: 20.0),
                      child: Text(widget.patientShareResponse.doctorNameObj,
                          style: TextStyle(
                              fontSize: 18.0,
                              color: Colors.grey[700],
                              fontWeight: FontWeight.bold)),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                          bottom: 10.0, left: 20.0, right: 20.0),
                      child: Text(
                          getDoctorSpeciality(
                              widget.patientShareResponse.doctorSpeciality),
                          style: TextStyle(
                              fontSize: 18.0, color: Colors.grey[700])),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                          top: 0.0, bottom: 10.0, left: 20.0, right: 20.0),
                      child: Text(widget.patientShareResponse.projectName,
                          style: TextStyle(
                              fontSize: 18.0, color: Colors.grey[700])),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                          top: 0.0, bottom: 10.0, left: 20.0, right: 20.0),
                      child: Text(
                          getDate(widget.patientShareResponse.appointmentDate),
                          style: TextStyle(
                              fontSize: 18.0, color: Colors.grey[700])),
                    ),
                  ],
                ),
              ),
              Container(
                alignment: Alignment.bottomCenter,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    ButtonTheme(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10.0),
                      ),
                      minWidth: MediaQuery.of(context).size.width * 0.7,
                      height: 45.0,
                      child: RaisedButton(
                        color: new Color(0xFF60686b),
                        textColor: Colors.white,
                        disabledTextColor: Colors.white,
                        disabledColor: new Color(0xFFbcc2c4),
                        onPressed: () {
//                    navigateToQR(context);
//                          getAppoQR(context);
                          sendEmail();
                        },
                        child: Text(
                            TranslationBase.of(context).sendEmail.toUpperCase(),
                            style: TextStyle(fontSize: 18.0)),
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                alignment: Alignment.bottomCenter,
                height: MediaQuery.of(context).size.height * 0.1,
                margin: EdgeInsets.only(bottom: 20.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    ButtonTheme(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10.0),
                      ),
                      minWidth: MediaQuery.of(context).size.width * 0.7,
                      height: 45.0,
                      child: RaisedButton(
                        color: new Color(0xFF60686b),
                        textColor: Colors.white,
                        disabledTextColor: Colors.white,
                        disabledColor: new Color(0xFFbcc2c4),
                        onPressed: () {
                          navigateToHome(context);
                        },
                        child: Text(
                            TranslationBase.of(context).close.toUpperCase(),
                            style: TextStyle(fontSize: 18.0)),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  sendEmail() async {
    DoctorsListService service = new DoctorsListService();

    if (await widget.sharedPref.getObject(USER_PROFILE) != null) {
      var data = AuthenticatedUser.fromJson(
          await widget.sharedPref.getObject(USER_PROFILE));
      setState(() {
        widget.authUser = data;
      });
    }

    ConfirmDialog dialog = new ConfirmDialog(
        context: context,
        confirmMessage: "Send a copy of this QR to the email " +
            widget.authUser.emailAddress +
            "?",
        okText: TranslationBase.of(context).confirm,
        cancelText: TranslationBase.of(context).cancel_nocaps,
        okFunction: () {
          service
              .sendAppointmentQREmail(
                  widget.authUser.emailAddress,
                  widget.patientShareResponse.appointmentDate,
                  widget.patientShareResponse.appointmentNo.toString(),
                  widget.patientShareResponse.doctorNameObj,
                  widget.patientShareResponse.projectName,
                  widget.appoQR,
                  getDoctorSpeciality(
                      widget.patientShareResponse.doctorSpeciality),
                  context)
              .then((res) {
            print(res);
            ConfirmDialog.closeAlertDialog(context);
          }).catchError((err) {
            ConfirmDialog.closeAlertDialog(context);
            AppToast.showErrorToast(message: err);
            print(err);
          }).showProgressBar(text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6));
        },
        cancelFunction: () => {});
    dialog.showAlertDialog(context);
  }

  Future navigateToHome(context) async {
    Navigator.of(context).pushNamed(HOME);
  }

  getPatientShare(context, String appointmentNo, int clinicID, int projectID,
      DoctorList docObject) {}

  String getDate(String appoDate) {
    var appoDateFormatted = "";

    var dateObj = DateUtil.convertStringToDate(appoDate);

    setState(() {
      appoDateFormatted = DateUtil.getWeekDay(dateObj.weekday) +
          ", " +
          dateObj.day.toString() +
          " " +
          DateUtil.getMonth(dateObj.month) +
          " " +
          dateObj.year.toString() +
          ", " +
          dateObj.hour.toString() +
          ":" +
          dateObj.minute.toString() +
          ":00";
    });

    return appoDateFormatted;
  }

  String getDoctorSpeciality(List<String> docSpecial) {
    String docSpeciality = "";
    docSpecial.forEach((v) {
      docSpeciality = docSpeciality + v + "\n";
    });
    return docSpeciality;
  }
}
