import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/model/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/core/service/AnalyticsService.dart';
import 'package:doctor_app_flutter/icons_app/doctor_app_icons.dart';
import 'package:doctor_app_flutter/locator.dart';
import 'package:doctor_app_flutter/utils/date-utils.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.dart';
import 'package:doctor_app_flutter/utils/utils.dart';
import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:intl/intl.dart';
import 'package:url_launcher/url_launcher_string.dart';

import 'header_row.dart';

class PatientProfileHeaderNewDesignAppBar extends StatelessWidget implements PreferredSizeWidget {
  final PatiantInformtion patient;
  final String patientType;
  final String arrivalType;
  final double height;
  final bool isInpatient;
  final bool isDischargedPatient;
  final bool isFromLiveCare;

  final Stream<String> videoCallDurationStream;

  PatientProfileHeaderNewDesignAppBar(this.patient, this.patientType, this.arrivalType,
      {this.height = 0.0, this.isInpatient = false, this.isDischargedPatient = false, this.isFromLiveCare = false, required this.videoCallDurationStream});

  @override
  Widget build(BuildContext context) {
    int gender = 1;
    if (patient.patientDetails != null) {
      gender = patient.patientDetails!.gender!;
    } else {
      gender = patient.gender!;
    }
    return Container(
      padding: EdgeInsets.only(
        left: 0,
        right: 5,
        bottom: 5,
      ),
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      height: height == 0
          ? isInpatient
              ? 220
              : 200
          : height,
      child: Container(
        padding: EdgeInsets.only(left: 10, right: 10, bottom: 10),
        margin: EdgeInsets.only(top: 50),
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.only(left: 12.0),
              child: Row(children: [
                IconButton(
                  icon: Icon(Icons.arrow_back_ios),
                  color: Colors.black, //Colors.black,
                  onPressed: () => Navigator.pop(context),
                ),
                Expanded(
                  child: AppText(
                    patient.firstName != null
                        ? (Utils.capitalize(patient.firstName) + " " + Utils.capitalize(patient.lastName))
                        : Utils.capitalize(patient.fullName ?? patient.patientDetails!.fullName),
                    fontSize: SizeConfig.textMultiplier! * 1.8,
                    fontWeight: FontWeight.bold,
                    fontFamily: 'Poppins',
                  ),
                ),
                gender == 1
                    ? Icon(
                        DoctorApp.male_2,
                        color: Colors.blue,
                      )
                    : Icon(
                        DoctorApp.female_1,
                        color: Colors.pink,
                      ),
                Container(
                  margin: EdgeInsets.symmetric(horizontal: 4),
                  child: InkWell(
                    onTap: () async {
                      await locator<AnalyticsService>().logEvent(
                        eventCategory: "Patient Profile Header",
                        eventAction: "Call Patient",
                      );
                      launchUrlString("tel://" + patient.mobileNumber!);
                    },
                    child: Icon(
                      Icons.phone,
                      color: Colors.black87,
                    ),
                  ),
                ),
                StreamBuilder(
                  stream: videoCallDurationStream,
                  builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
                    if (snapshot.hasData && snapshot.data != null)
                      return InkWell(
                        onTap: () {},
                        child: Container(
                          decoration: BoxDecoration(color: Colors.red, borderRadius: BorderRadius.circular(20)),
                          padding: EdgeInsets.symmetric(vertical: 2, horizontal: 10),
                          child: Text(
                            snapshot.data!,
                            style: TextStyle(color: Colors.white),
                          ),
                        ),
                      );
                    else
                      return Container();
                  },
                ),
              ]),
            ),
            Row(children: [
              Padding(
                padding: EdgeInsets.only(left: 12.0),
                child: Container(
                  width: 60,
                  height: 60,
                  child: Image.asset(
                    gender == 1 ? 'assets/images/male_avatar.png' : 'assets/images/female_avatar.png',
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              SizedBox(
                width: 10,
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SERVICES_PATIANT2[int.parse(patientType)] == "patientArrivalList"
                        ? Container(
                            child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              if (patient.patientStatusType != null)
                                patient.patientStatusType == 43
                                    ? AppText(
                                        TranslationBase.of(context).arrivedP,
                                        color: AppGlobal.appGreenColor,
                                        fontWeight: FontWeight.bold,
                                        fontFamily: 'Poppins',
                                        fontSize: 12,
                                      )
                                    : AppText(
                                        TranslationBase.of(context).notArrived,
                                        color: Colors.red[800]!,
                                        fontWeight: FontWeight.bold,
                                        fontFamily: 'Poppins',
                                        fontSize: 12,
                                      ),
                              arrivalType == '1' || patient.arrivedOn == null
                                  ? AppText(
                                      patient.startTime != null ? patient.startTime! : '',
                                      fontFamily: 'Poppins',
                                      fontWeight: FontWeight.w600,
                                    )
                                  : AppText(
                                      patient.arrivedOn != null ? AppDateUtils.convertStringToDateFormat(patient.arrivedOn!, 'MM-dd-yyyy HH:mm') : '',
                                      fontFamily: 'Poppins',
                                      fontWeight: FontWeight.w600,
                                    )
                            ],
                          ))
                        : SizedBox(),
                    if (SERVICES_PATIANT2[int.parse(patientType)] == "List_MyOutPatient" && !isFromLiveCare)
                      Container(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: <Widget>[
                            AppText(
                              TranslationBase.of(context).appointmentDate + " : ",
                              fontSize: 14,
                            ),
                            patient.startTime != null
                                ? Container(
                                    height: 15,
                                    width: 60,
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(25),
                                      color: HexColor("#20A169"),
                                    ),
                                    child: AppText(
                                      patient.startTime ?? "",
                                      color: Colors.white,
                                      fontSize: 1.5 * SizeConfig.textMultiplier!,
                                      textAlign: TextAlign.center,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  )
                                : SizedBox(),
                            SizedBox(
                              width: 3.5,
                            ),
                            Container(
                              child: AppText(
                                convertDateFormat2(patient.appointmentDate ?? ''),
                                fontSize: 1.5 * SizeConfig.textMultiplier!,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            SizedBox(
                              height: 0.5,
                            )
                          ],
                        ),
                        margin: EdgeInsets.only(
                          top: 8,
                        ),
                      ),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        HeaderRow(
                          label: TranslationBase.of(context).fileNumber,
                          value: patient.patientId.toString(),
                        ),
                        Expanded(
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Expanded(
                                child: Container(
                                  alignment: Alignment.centerRight,
                                  child: AppText(
                                    patient.nationalityName ?? patient.nationality ?? patient.nationalityId ?? '',
                                    fontWeight: FontWeight.bold,
                                    fontSize: 12,
                                  ),
                                ),
                              ),
                              patient.nationalityFlagURL != null
                                  ? ClipRRect(
                                      borderRadius: BorderRadius.circular(20.0),
                                      child: Image.network(
                                        patient.nationalityFlagURL!,
                                        height: 25,
                                        width: 30,
                                        errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) {
                                          return Text('');
                                        },
                                      ))
                                  : SizedBox()
                            ],
                          ),
                        )
                      ],
                    ),
                    HeaderRow(
                      label: TranslationBase.of(context).age + " : ",
                      value:
                          "${AppDateUtils.getAgeByBirthday(patient.patientDetails != null ? patient.patientDetails!.dateofBirth ?? "" : patient.dateofBirth ?? "", context, isServerFormat: !isFromLiveCare)}",
                    ),
                    if (isInpatient)
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          HeaderRow(
                              label: patient.admissionDate == null ? "" : TranslationBase.of(context).admissionDate + " : ",
                              value: patient.admissionDate == null ? "" : "${AppDateUtils.convertDateFromServerFormat(patient.admissionDate.toString(), 'yyyy-MM-dd')}"),
                          if (patient.admissionDate != null)
                            HeaderRow(
                              label: "${TranslationBase.of(context).numOfDays}: ",
                              value: isDischargedPatient && patient.dischargeDate != null
                                  ? "${AppDateUtils.getDateTimeFromServerFormat(patient.dischargeDate!).difference(AppDateUtils.getDateTimeFromServerFormat(patient.admissionDate!)).inDays + 1}"
                                  : "${DateTime.now().difference(AppDateUtils.getDateTimeFromServerFormat(patient.admissionDate!)).inDays + 1}",
                            )
                        ],
                      )
                  ],
                ),
              ),
            ]),
          ],
        ),
      ),
    );
  }

  convertDateFormat2(String str) {
    String? newDate;
    const start = "/Date(";
    if (str.isNotEmpty) {
      const end = "+0300)";

      final startIndex = str.indexOf(start);
      final endIndex = str.indexOf(end, startIndex + start.length);

      var date = new DateTime.fromMillisecondsSinceEpoch(int.parse(str.substring(startIndex + start.length, endIndex)));
      newDate = date.year.toString() + "/" + date.month.toString().padLeft(2, '0') + "/" + date.day.toString().padLeft(2, '0');
    }

    return newDate ?? '';
  }

  isToday(date) {
    DateTime tempDate = new DateFormat("yyyy-MM-dd").parse(date);
    return DateFormat("yyyy-MM-dd").format(tempDate) == DateFormat("yyyy-MM-dd").format(DateTime.now());
  }

  myBoxDecoration() {
    return BoxDecoration(
        border: Border(
          top: BorderSide(
            color: AppGlobal.appGreenColor,
            width: 5,
          ),
        ),
        borderRadius: BorderRadius.circular(10));
  }

  @override
  Size get preferredSize => Size(double.maxFinite, 200);
}
