import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/cupertino.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/date_util.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/insurance/insurance_view_model.dart';
import 'package:hmg_patient_app_new/features/insurance/models/resp_models/patient_insurance_details_response_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/insurance/widgets/insurance_update_details_card.dart';
import 'package:hmg_patient_app_new/theme/colors.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:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

class PatientInsuranceCard extends StatelessWidget {
  PatientInsuranceCard({super.key, required this.insuranceCardDetailsModel, required this.isInsuranceExpired, this.isShowButtons = true});

  PatientInsuranceDetailsResponseModel insuranceCardDetailsModel;
  bool isInsuranceExpired = false;
  bool isShowButtons = true;

  late InsuranceViewModel insuranceViewModel;
  late AppState appState;

  @override
  Widget build(BuildContext context) {
    appState = getIt.get<AppState>();
    insuranceViewModel = Provider.of<InsuranceViewModel>(context);
    return Container(
      width: double.infinity,
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.r,
      ),
      child: Padding(
        padding: EdgeInsets.all(16.h),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(
                        width: MediaQuery.of(context).size.width * 0.4,
                        child: "${appState.getAuthenticatedUser()!.firstName} ${appState.getAuthenticatedUser()!.lastName}".toText18(isBold: true, textOverflow: TextOverflow.clip, isEnglishOnly: true)),
                    LocaleKeys.policyNumberInsurancePage.tr(namedArgs: {'number': insuranceCardDetailsModel.insurancePolicyNo.toString()}).toText12(isBold: true, color: AppColors.lightGrayColor, isEnglishOnly: true),
                    // Row(
                    //   children: [
                    //     "${LocaleKeys.policyNumber.tr(context: context)}${insuranceCardDetailsModel.insurancePolicyNo}".toText12(isBold: true, color: AppColors.lightGrayColor),
                    //   ],
                    // ),
                  ],
                ),
                isShowButtons ? AppCustomChipWidget(
                  icon: isCurrentPatientInsuranceExpired(insuranceCardDetailsModel.cardValidTo!)
                      ? AppAssets.cancel_circle_icon
                      : insuranceViewModel.isInsuranceActive
                          ? AppAssets.insurance_active_icon
                          : AppAssets.alertSquare,
                  labelText: isCurrentPatientInsuranceExpired(insuranceCardDetailsModel.cardValidTo!)
                      ? LocaleKeys.insuranceExpired.tr(context: context)
                      : insuranceViewModel.isInsuranceActive
                          ? LocaleKeys.insuranceActive.tr(context: context)
                          : LocaleKeys.insuranceInActive.tr(context: context),
                  iconColor: isCurrentPatientInsuranceExpired(insuranceCardDetailsModel.cardValidTo!)
                      ? AppColors.primaryRedColor
                      : insuranceViewModel.isInsuranceActive
                          ? AppColors.successColor
                          : AppColors.warningColorYellow,
                  textColor: isCurrentPatientInsuranceExpired(insuranceCardDetailsModel.cardValidTo!)
                      ? AppColors.primaryRedColor
                      : insuranceViewModel.isInsuranceActive
                          ? AppColors.successColor
                          : AppColors.warningColorYellow,
                  iconSize: 12.w,
                  deleteIcon: insuranceViewModel.isInsuranceActive ? null : AppAssets.forward_chevron_icon,
                  deleteIconColor: insuranceViewModel.isInsuranceExpired
                      ? AppColors.primaryRedColor
                      : insuranceViewModel.isInsuranceActive
                          ? AppColors.successColor
                          : AppColors.warningColorYellow,
                  deleteIconHasColor: true,
                  onChipTap: () {
                    if (!insuranceViewModel.isInsuranceActive) {
                      insuranceViewModel.setIsInsuranceUpdateDetailsLoading(true);
                      insuranceViewModel.getPatientInsuranceDetailsForUpdate(
                          appState.getAuthenticatedUser()!.patientId.toString(), appState.getAuthenticatedUser()!.patientIdentificationNo.toString());
                      showCommonBottomSheetWithoutHeight(context, child: PatientInsuranceCardUpdateCard(), callBackFunc: () {}, title: "", isCloseButtonVisible: false, isFullScreen: false);
                      // showCommonBottomSheetWithoutHeight(
                      //   title: LocaleKeys.notice.tr(context: context),
                      //   context,
                      //   child: Utils.getWarningWidget(
                      //       loadingText: LocaleKeys.insuranceInActiveContactSupport.tr(context: context),
                      //       confirmText: LocaleKeys.contactUs.tr(context: context),
                      //       isShowActionButtons: true,
                      //       onCancelTap: () {
                      //         Navigator.pop(context);
                      //       },
                      //       onConfirmTap: () async {
                      //         launchUrl(Uri.parse("tel://" + "+966 92 006 6666"));
                      //       }),
                      //   callBackFunc: () {},
                      //   isFullScreen: false,
                      //   isCloseButtonVisible: true,
                      // );
                    }
                  },
                  backgroundColor: isCurrentPatientInsuranceExpired(insuranceCardDetailsModel.cardValidTo!)
                      ? AppColors.primaryRedColor.withOpacity(0.1)
                      : insuranceViewModel.isInsuranceActive
                          ? AppColors.successColor.withOpacity(0.1)
                          : AppColors.warningColorYellow.withOpacity(0.1),
                  labelPadding: EdgeInsetsDirectional.only(start: -4.w, end: insuranceViewModel.isInsuranceActive ? 6.w : 0.w),
                ).toShimmer2(isShow: insuranceViewModel.isInsuranceLoading) : SizedBox.shrink(),
                // AppCustomChipWidget(
                //   icon: isInsuranceExpired ? AppAssets.cancel_circle_icon : AppAssets.insurance_active_icon,
                //   labelText: isInsuranceExpired ? LocaleKeys.insuranceExpired.tr(context: context) : LocaleKeys.insuranceActive.tr(context: context),
                //   iconColor: isInsuranceExpired ? AppColors.primaryRedColor : AppColors.successColor,
                //   textColor: isInsuranceExpired ? AppColors.primaryRedColor : AppColors.successColor,
                //   iconSize: 12,
                //   backgroundColor: isInsuranceExpired ? AppColors.primaryRedColor.withOpacity(0.1) : AppColors.successColor.withOpacity(0.1),
                //   labelPadding: EdgeInsetsDirectional.only(start: -4.h, end: 8.h),
                // ),
              ],
            ),
            SizedBox(height: 12.h),
            insuranceCardDetailsModel.groupName!.toText12(isBold: true, isEnglishOnly: true),
            Row(
              children: [
                (insuranceCardDetailsModel.companyName!.length > 40 ? "${insuranceCardDetailsModel.companyName!.substring(0, 40)}..." : insuranceCardDetailsModel.companyName!).toText12(isBold: true, isEnglishOnly: true),
                SizedBox(
                  width: 6.h,
                ),
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 6.h, vertical: 4.h),
                  decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                    color: AppColors.infoColor,
                    borderRadius: 50.r,
                  ),
                  child: ((insuranceCardDetailsModel.subCategoryDesc ?? "").length > 10 ? (insuranceCardDetailsModel.subCategoryDesc ?? "").substring(0, 10) : (insuranceCardDetailsModel.subCategoryDesc ?? ""))
                      .toText8(isBold: true, color: AppColors.whiteColor, isEnglishOnly: true),
                ),
              ],
            ),
            SizedBox(height: 8.h),
            Wrap(
              direction: Axis.horizontal,
              spacing: 4.h,
              runSpacing: 4.h,
              children: [
                AppCustomChipWidget(
                    icon: AppAssets.doctor_calendar_icon,
                  // labelText: "${LocaleKeys.expiryDate.tr(context: context)} ${DateUtil.formatDateToDate(DateUtil.convertStringToDate(insuranceCardDetailsModel.cardValidTo), false)}",
                  richText:
                      "${LocaleKeys.expiryDate.tr(context: context)} ${DateUtil.formatDateToDate(DateUtil.convertStringToDate(insuranceCardDetailsModel.cardValidTo), false)}".toText10(isBold: true),
                  labelPadding: EdgeInsetsDirectional.only(start: -4.h, end: 8.h),
                ),
                AppCustomChipWidget(richText: LocaleKeys.patientCardID.tr(namedArgs: {'id': insuranceCardDetailsModel.patientCardID ?? ''}, context: context).toText10(isBold: true)),
              ],
            ),
            SizedBox(height: 10.h),
            isInsuranceExpired
                ? isShowButtons ? CustomButton(
                    icon: AppAssets.update_insurance_card_icon,
                    iconColor: AppColors.warningColorYellow,
                    iconSize: 15.h,
                    // text: "${LocaleKeys.updateInsurance.tr(context: context)} ${LocaleKeys.updateInsuranceSubtitle.tr(context: context)}",
                    text: LocaleKeys.verifyInsurance.tr(context: context),
                    onPressed: () {
                      insuranceViewModel.setIsInsuranceUpdateDetailsLoading(true);
                      insuranceViewModel.getPatientInsuranceDetailsForUpdate(
                          appState.getAuthenticatedUser()!.patientId.toString(), appState.getAuthenticatedUser()!.patientIdentificationNo.toString());
                      showCommonBottomSheetWithoutHeight(context,
                          child: PatientInsuranceCardUpdateCard(),
                          callBackFunc: () {},
                          title: "",
                          // height: ResponsiveExtension.screenHeight * 0.42,
                          isCloseButtonVisible: false,
                          isFullScreen: false);
                    },
                    backgroundColor: AppColors.warningColorYellow.withOpacity(0.20),
                    borderColor: AppColors.warningColorYellow.withOpacity(0.0),
                    textColor: AppColors.warningColorYellow,
                    fontSize: 14,
                    isBold: true,
                    borderRadius: 12,
                    padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                    height: 40.h,
                  ) : SizedBox.shrink()
                : Container(),
          ],
        ),
      ),
    ).paddingSymmetrical(0.h, 0.h);
  }

  bool isCurrentPatientInsuranceExpired(String cardValidTo) {
    return DateTime.now().isAfter(
      DateUtil.convertStringToDate(cardValidTo),
    );
  }
}
