import 'dart:io';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_model.dart';
import 'package:hmg_patient_app_new/features/immediate_livecare/immediate_livecare_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/livecare/immediate_livecare_payment_page.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/livecare/widgets/select_livecare_call_type.dart';
import 'package:hmg_patient_app_new/presentation/insurance/insurance_home_page.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart';
import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart';
import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart';
import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:smooth_corner/smooth_corner.dart';

class ImmediateLiveCarePaymentDetails extends StatelessWidget {
  ImmediateLiveCarePaymentDetails({super.key});

  late ImmediateLiveCareViewModel immediateLiveCareViewModel;
  late AppState appState;

  @override
  Widget build(BuildContext context) {
    immediateLiveCareViewModel = Provider.of<ImmediateLiveCareViewModel>(context, listen: false);
    appState = getIt.get<AppState>();
    return Scaffold(
      backgroundColor: AppColors.scaffoldBgColor,
      body: Column(
        children: [
          Expanded(
            child: CollapsingListView(
              title: "Review LiveCare Request".needTranslation,
              child: SingleChildScrollView(
                padding: EdgeInsets.symmetric(horizontal: 24.h),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 24.h),
                    LocaleKeys.patientInfo.tr(context: context).toText16(isBold: true),
                    SizedBox(height: 16.h),
                    Container(
                      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                        color: AppColors.whiteColor,
                        borderRadius: 24.h,
                        hasShadow: false,
                      ),
                      child: Padding(
                        padding: EdgeInsets.all(16.h),
                        child: Row(
                          children: [
                            Image.asset(
                              appState.getAuthenticatedUser()?.gender == 1 ? AppAssets.male_img : AppAssets.femaleImg,
                              width: 52.h,
                              height: 52.h,
                            ),
                            SizedBox(width: 8.h),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                "${appState.getAuthenticatedUser()!.firstName} ${appState.getAuthenticatedUser()!.lastName}".toText16(isBold: true),
                                SizedBox(height: 8.h),
                                AppCustomChipWidget(labelText: "${appState.getAuthenticatedUser()!.age} Years Old"),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                    SizedBox(height: 24.h),
                    "Clinic Information".needTranslation.toText16(isBold: true),
                    SizedBox(height: 16.h),
                    Container(
                      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                        color: AppColors.whiteColor,
                        borderRadius: 24.h,
                        hasShadow: false,
                      ),
                      child: Padding(
                        padding: EdgeInsets.all(16.h),
                        child: Row(
                          children: [
                            Utils.buildSvgWithAssets(icon: AppAssets.generic_clinic_icon, width: 32.h, height: 32.h, fit: BoxFit.contain),
                            SizedBox(width: 8.h),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                (appState.isArabic()
                                        ? immediateLiveCareViewModel.immediateLiveCareSelectedClinic.serviceNameN
                                        : immediateLiveCareViewModel.immediateLiveCareSelectedClinic.serviceName)!
                                    .toText16(isBold: true),
                                // SizedBox(height: 8.h),
                                // AppCustomChipWidget(labelText: "${appState.getAuthenticatedUser()!.age} Years Old"),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                    SizedBox(height: 24.h),
                    "Selected LiveCare Type".needTranslation.toText16(isBold: true),
                    SizedBox(height: 16.h),
                    Consumer<BookAppointmentsViewModel>(builder: (context, bookAppointmentsVM, child) {
                      return Container(
                        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                          color: AppColors.whiteColor,
                          borderRadius: 24.h,
                          hasShadow: false,
                        ),
                        child: Padding(
                          padding: EdgeInsets.all(16.h),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  Utils.buildSvgWithAssets(icon: AppAssets.livecare_clinic_icon, width: 32.h, height: 32.h, fit: BoxFit.contain),
                                  SizedBox(width: 8.h),
                                  getLiveCareType(immediateLiveCareViewModel.liveCareSelectedCallType).toText16(isBold: true),
                                ],
                              ),
                              Utils.buildSvgWithAssets(icon: AppAssets.edit_icon, width: 24.h, height: 24.h, fit: BoxFit.contain),
                            ],
                          ),
                        ),
                      ).onPress(() {
                        showCommonBottomSheetWithoutHeight(context, child: SelectLiveCareCallType(immediateLiveCareViewModel: immediateLiveCareViewModel), callBackFunc: () async {
                          debugPrint("Selected Call Type: ${immediateLiveCareViewModel.liveCareSelectedCallType}");
                        }, title: "Select LiveCare call type".needTranslation, isCloseButtonVisible: true, isFullScreen: false);
                      });
                    }),
                    SizedBox(height: 24.h)
                  ],
                ),
              ),
            ),
          ),
          Container(
            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
              color: AppColors.whiteColor,
              borderRadius: 24.h,
              hasShadow: false,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                (immediateLiveCareViewModel.liveCareImmediateAppointmentFeesList.isCash ?? true)
                    ? Container(
                        height: 50.h,
                        decoration: ShapeDecoration(
                          color: AppColors.secondaryLightRedBorderColor,
                          shape: SmoothRectangleBorder(
                            borderRadius: BorderRadius.only(topLeft: Radius.circular(24), topRight: Radius.circular(24)),
                            smoothness: 1,
                          ),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            "Insurance expired or inactive".needTranslation.toText14(color: AppColors.primaryRedColor, weight: FontWeight.w500).paddingSymmetrical(24.h, 0.h),
                            CustomButton(
                              text: LocaleKeys.updateInsurance.tr(context: context),
                              onPressed: () {
                                Navigator.of(context).push(
                                  CustomPageRoute(
                                    page: InsuranceHomePage(),
                                  ),
                                );
                              },
                              backgroundColor: AppColors.primaryRedColor,
                              borderColor: AppColors.secondaryLightRedBorderColor,
                              textColor: AppColors.whiteColor,
                              fontSize: 10,
                              fontWeight: FontWeight.w500,
                              borderRadius: 8,
                              padding: EdgeInsets.fromLTRB(15, 0, 15, 0),
                              height: 30.h,
                            ).paddingSymmetrical(24.h, 0.h),
                          ],
                        ),
                      )
                    : const SizedBox(),
                SizedBox(height: 24.h),
                "Total amount to pay".needTranslation.toText18(isBold: true).paddingSymmetrical(24.h, 0.h),
                SizedBox(height: 17.h),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    "Amount before tax".needTranslation.toText14(isBold: true),
                    Utils.getPaymentAmountWithSymbol(immediateLiveCareViewModel.liveCareImmediateAppointmentFeesList.amount!.toText16(isBold: true), AppColors.blackColor, 13,
                        isSaudiCurrency: immediateLiveCareViewModel.liveCareImmediateAppointmentFeesList.currency!.toLowerCase() == "sar"),
                  ],
                ).paddingSymmetrical(24.h, 0.h),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    "VAT 15%".needTranslation.toText14(isBold: true, color: AppColors.greyTextColor),
                    Utils.getPaymentAmountWithSymbol(
                        immediateLiveCareViewModel.liveCareImmediateAppointmentFeesList.tax!.toText14(isBold: true, color: AppColors.greyTextColor), AppColors.greyTextColor, 13,
                        isSaudiCurrency: immediateLiveCareViewModel.liveCareImmediateAppointmentFeesList.currency!.toLowerCase() == "sar"),
                  ],
                ).paddingSymmetrical(24.h, 0.h),
                SizedBox(height: 17.h),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    SizedBox(width: 150.h, child: Utils.getPaymentMethods()),
                    Utils.getPaymentAmountWithSymbol(immediateLiveCareViewModel.liveCareImmediateAppointmentFeesList.total!.toText24(isBold: true), AppColors.blackColor, 17,
                        isSaudiCurrency: immediateLiveCareViewModel.liveCareImmediateAppointmentFeesList.currency!.toLowerCase() == "sar"),
                  ],
                ).paddingSymmetrical(24.h, 0.h),
                CustomButton(
                  text: LocaleKeys.payNow.tr(context: context),
                  onPressed: () async {
                    await askVideoCallPermission().then((val) {
                      if (val) {
                        Navigator.of(context).push(
                          CustomPageRoute(
                            page: ImmediateLiveCarePaymentPage(),
                          ),
                        );
                      } else {
                        showCommonBottomSheetWithoutHeight(
                          title: LocaleKeys.notice.tr(context: context),
                          context,
                          child: Utils.getWarningWidget(
                              loadingText:
                                  "LiveCare requires Camera, Microphone & Location permissions to enable virtual consultation between patient & doctor, Please allow these to proceed.".needTranslation,
                              isShowActionButtons: true,
                              onCancelTap: () {
                                Navigator.pop(context);
                              },
                              onConfirmTap: () async {
                                openAppSettings();
                              }),
                          callBackFunc: () {},
                          isFullScreen: false,
                          isCloseButtonVisible: true,
                        );
                      }
                    });
                  },
                  backgroundColor: AppColors.infoColor,
                  borderColor: AppColors.infoColor,
                  textColor: AppColors.whiteColor,
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                  borderRadius: 12,
                  padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                  height: 50.h,
                  icon: AppAssets.appointment_pay_icon,
                  iconColor: AppColors.whiteColor,
                  iconSize: 18.h,
                ).paddingSymmetrical(24.h, 24.h),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Future<bool> askVideoCallPermission() async {
    Map<Permission, PermissionStatus> statuses = await [
      Permission.camera,
      Permission.microphone,
    ].request();

    if (statuses[Permission.camera] == PermissionStatus.granted && statuses[Permission.microphone] == PermissionStatus.granted) {
      // Camera permission granted
      return true;
    } else {
      return false;
    }

    // if (!(await Permission.camera.request().isGranted) || !(await Permission.microphone.request().isGranted)) {
    //   return false;
    // }
  }

  String getLiveCareType(int callType) {
    switch (callType) {
      case 1:
        return "Video Call".needTranslation;
      case 2:
        return "Audio Call".needTranslation;
      case 3:
        return "Phone Call".needTranslation;
      default:
        return "Video Call".needTranslation;
    }
  }
}
