import 'dart:developer';
import 'dart:io';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.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/route_extensions.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/hmg_services/hmg_services_view_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/req_models/cmc_create_new_order_req_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/get_cmc_services_resp_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/hospital_model.dart';
import 'package:hmg_patient_app_new/features/payfort/payfort_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/comprehensive_checkup/widgets/cmc_ui_selection_helper.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/common_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:hmg_patient_app_new/widgets/map/location_map_widget.dart';
import 'package:map_launcher/map_launcher.dart';
import 'package:provider/provider.dart';

class CmcSelectionReviewPage extends StatefulWidget {
  final GetCMCServicesResponseModel selectedService;
  final HospitalsModel? preSelectedHospital;

  const CmcSelectionReviewPage({super.key, required this.selectedService, this.preSelectedHospital});

  @override
  State<CmcSelectionReviewPage> createState() => _CmcSelectionReviewPageState();
}

class _CmcSelectionReviewPageState extends State<CmcSelectionReviewPage> {
  @override
  void initState() {
    super.initState();
    // Initialize ViewModel state with preselected hospital if provided
    if (widget.preSelectedHospital != null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        final hmgServicesViewModel = context.read<HmgServicesViewModel>();
        hmgServicesViewModel.setSelectedHospitalForOrder(widget.preSelectedHospital);
        hmgServicesViewModel.setSelectedServiceForOrder(widget.selectedService);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final appState = getIt.get<AppState>();
    final isArabic = appState.isArabic();

    return CollapsingListView(
      title: LocaleKeys.summary.tr(context: context),
      bottomChild: _buildBottomButton(),
      child: SingleChildScrollView(
        padding: EdgeInsets.all(16.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildOrderSummaryCard(isArabic),
            SizedBox(height: 16.h),
            _buildSelectedServiceCard(isArabic),
            SizedBox(height: 16.h),
            _buildPaymentSummary(),
          ],
        ),
      ),
    );
  }

  Widget _buildOrderSummaryCard(bool isArabic) {
    return Consumer<HmgServicesViewModel>(
      builder: (context, hmgServicesViewModel, child) {
        final selectedHospital = hmgServicesViewModel.selectedHospitalForOrder;
        final isLocationSelected = selectedHospital != null;

        return Container(
          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
            color: AppColors.whiteColor,
            borderRadius: 16.r,
          ),
          padding: EdgeInsets.all(16.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                LocaleKeys.selectHospital.tr(context: context),
                style: TextStyle(
                  fontSize: 16.f,
                  fontWeight: FontWeight.w700,
                  color: AppColors.blackColor,
                  letterSpacing: -0.5,
                ),
              ),
              SizedBox(height: 12.h),
              _buildHospitalSelector(isArabic, selectedHospital, isLocationSelected),
              if (isLocationSelected) ...[
                SizedBox(height: 16.h),
                _buildHospitalMap(selectedHospital),
              ],
            ],
          ),
        );
      },
    );
  }

  Widget _buildHospitalSelector(bool isArabic, HospitalsModel? selectedHospital, bool isLocationSelected) {
    return InkWell(
      onTap: _showHospitalSelectionBottomSheet,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 14.h),
        decoration: BoxDecoration(
          color: AppColors.bgScaffoldColor,
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(
            color: AppColors.greyColor.withAlpha(51),
            width: 1,
          ),
        ),
        child: Row(
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    isLocationSelected && selectedHospital != null
                        ? (isArabic ? (selectedHospital.nameN ?? selectedHospital.name ?? '') : (selectedHospital.name ?? ''))
                        : LocaleKeys.selectHospital.tr(context: context),
                    style: TextStyle(
                      fontSize: 14.f,
                      fontWeight: isLocationSelected ? FontWeight.w600 : FontWeight.w400,
                      color: isLocationSelected ? AppColors.blackColor : AppColors.greyTextColor,
                      letterSpacing: -0.4,
                    ),
                  ),
                ],
              ),
            ),
            Icon(
              Icons.keyboard_arrow_down,
              color: AppColors.greyTextColor,
              size: 24.h,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildHospitalMap(HospitalsModel selectedHospital) {
    final String lat = ((selectedHospital.latitude == null || selectedHospital.latitude!.isEmpty) ? "0.0" : selectedHospital.latitude) ?? "0.0";
    final String lng = ((selectedHospital.longitude == null || selectedHospital.longitude!.isEmpty) ? "0.0" : selectedHospital.longitude) ?? "0.0";

    log("selectedHospital: $lng and $lat");

    if (lat == "0.0" || lng == "0.0") return SizedBox.shrink();

    final appState = getIt.get<AppState>();
    final isArabic = appState.isArabic();
    final hospitalName = isArabic ? (selectedHospital.nameN ?? selectedHospital.name ?? '') : (selectedHospital.name ?? '');

    return LocationMapWidget(
      latitude: double.parse(lat),
      longitude: double.parse(lng),
      address: hospitalName,
      showAddress: false,
      padding: EdgeInsets.zero,
      onDirectionsTap: () => _launchDirections(selectedHospital),
    );
  }

  Widget _buildSelectedServiceCard(bool isArabic) {
    final serviceName = isArabic ? (widget.selectedService.textN ?? widget.selectedService.text ?? '') : (widget.selectedService.text ?? '');
    final price = widget.selectedService.priceTotal ?? 0.0;

    return Container(
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 16.r,
      ),
      padding: EdgeInsets.all(16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          LocaleKeys.selectedService.tr(context: context).toText14(
                weight: FontWeight.w600,
                color: AppColors.greyTextColor,
                letterSpacing: -0.4,
              ),
          SizedBox(height: 6.h),
          Row(
            children: [
              Expanded(child: serviceName.toText16(weight: FontWeight.w700, color: AppColors.blackColor, letterSpacing: -0.5)),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildPaymentSummary() {
    // Use selected service from widget
    final service = widget.selectedService;

    log("service: ${service.toJson()}");

    final double amountBeforeTax = service.price ?? 0.0;
    final double taxAmount = service.priceVAT ?? 0.0;
    final double totalAmount = service.priceTotal ?? (amountBeforeTax + taxAmount);

    return Container(
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.h,
        hasShadow: false,
      ),
      child: Consumer<PayfortViewModel>(builder: (context, payfortVM, child) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(height: 24.h),
            LocaleKeys.totalAmountToPay.tr(context: context).toText18(isBold: true).paddingSymmetrical(24.h, 0.h),
            SizedBox(height: 17.h),

            // Amount before tax
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                LocaleKeys.amountBeforeTax.tr(context: context).toText14(isBold: true),
                Utils.getPaymentAmountWithSymbol(
                  amountBeforeTax.toString().toText16(isBold: true),
                  AppColors.blackColor,
                  13,
                  isSaudiCurrency: true,
                ),
              ],
            ).paddingSymmetrical(24.h, 0.h),

            // VAT (use label VAT 15% if desired)
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                LocaleKeys.vat15.tr(context: context).toText14(isBold: true, color: AppColors.greyTextColor),
                Utils.getPaymentAmountWithSymbol(
                  taxAmount.toString().toText14(isBold: true, color: AppColors.greyTextColor),
                  AppColors.greyTextColor,
                  13,
                  isSaudiCurrency: true,
                ),
              ],
            ).paddingSymmetrical(24.h, 0.h),
            SizedBox(height: 17.h),
            // Total Amount
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                "".toText14(isBold: true),
                Utils.getPaymentAmountWithSymbol(
                  totalAmount.toString().toText24(isBold: true),
                  AppColors.blackColor,
                  17,
                  isSaudiCurrency: true,
                ),
              ],
            ).paddingSymmetrical(24.h, 0.h),

            SizedBox(height: 16.h),
          ],
        );
      }),
    );
  }

  Widget _buildBottomButton() {
    return Consumer<HmgServicesViewModel>(
      builder: (context, hmgServicesViewModel, child) {
        final isLocationSelected = hmgServicesViewModel.selectedHospitalForOrder != null;

        return SafeArea(
          top: false,
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
            decoration: BoxDecoration(
              color: AppColors.whiteColor,
              boxShadow: [
                BoxShadow(
                  color: Color.fromARGB(13, 0, 0, 0),
                  blurRadius: 8,
                  offset: Offset(0, -2),
                ),
              ],
            ),
            child: CustomButton(
              text: LocaleKeys.confirm.tr(context: context),
              onPressed: () {
                isLocationSelected ? _handleConfirm() : null;
              },
              textColor: AppColors.whiteColor,
              backgroundColor: isLocationSelected ? AppColors.successColor : AppColors.greyColor,
              borderRadius: 12.r,
              borderColor: Colors.transparent,
              borderWidth: 0,
              padding: EdgeInsets.symmetric(vertical: 14.h),
            ),
          ),
        );
      },
    );
  }

  void _showHospitalSelectionBottomSheet() {
    CmcUiSelectionHelper.showHospitalSelectionBottomSheet(context: context, onHospitalSelected: (hospital) => context.pop());
  }

  void _launchDirections(HospitalsModel selectedHospital) async {
    final double lat = double.parse(selectedHospital.latitude ?? "0.0");
    final double lng = double.parse(selectedHospital.longitude ?? "0.0");

    if (lat != 0.0 && lng != 0.0) {
      await MapLauncher.showMarker(
        mapType: MapType.google,
        coords: Coords(lat, lng),
        title: selectedHospital.name ?? "Hospital",
      ).catchError((err) {
        MapLauncher.showMarker(
          mapType: Platform.isIOS ? MapType.apple : MapType.google,
          coords: Coords(lat, lng),
          title: selectedHospital.name ?? "Hospital",
        );
      });
      // MapsLauncher.launchCoordinates(
      //   lat,
      //   lng,
      //   selectedHospital.name ?? "Hospital",
      // );
    }
  }

  showSuccessBottomSheet(int requestId, HmgServicesViewModel hmgServicesViewModel) {
    return showCommonBottomSheetWithoutHeight(
      context,
      child: Padding(
        padding: EdgeInsets.all(16.w),
        child: Column(
          children: [
            Utils.getSuccessWidget(loadingText: LocaleKeys.requestSubmittedSuccessfully.tr(context: context)),
            Row(
              children: [
                LocaleKeys.hereIsYourRequestNumber.tr(context: context).toText14(
                      color: AppColors.textColorLight,
                      weight: FontWeight.w600,
                    ),
                SizedBox(width: 4.w),
                ("$requestId").toText16(isBold: true),
              ],
            ),
            SizedBox(height: 24.h),
            Row(
              children: [
                Expanded(
                  child: CustomButton(
                    height: 56.h,
                    text: LocaleKeys.ok.tr(),
                    onPressed: () {
                      context.pop();
                      context.pop();
                      hmgServicesViewModel.getAllCmcOrders();
                    },
                    textColor: AppColors.whiteColor,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
      isCloseButtonVisible: false,
      isDismissible: false,
      isFullScreen: false,
        isAutoDismiss: true);
  }

  void _handleConfirm() {
    final hmgServicesViewModel = context.read<HmgServicesViewModel>();
    final selectedHospital = hmgServicesViewModel.selectedHospitalForOrder;

    if (selectedHospital == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(LocaleKeys.pleaseSelectHospitalToContinue.tr(context: context)),
          backgroundColor: AppColors.errorColor,
        ),
      );
      return;
    }

    final selectedService = widget.selectedService;
    return showCommonBottomSheetWithoutHeight(
      title: LocaleKeys.notice.tr(context: context),
      context,
      child: Utils.getWarningWidget(
          loadingText: LocaleKeys.confirmSubmitRequest.tr(context: context),
          isShowActionButtons: true,
          onCancelTap: () {
            Navigator.pop(context);
          },
          onConfirmTap: () async {
            Navigator.pop(context);
            LoaderBottomSheet.showLoader();

            // Create the services list
            final servicesList = [
              PatientERCMCInsertServicesList(
                recordID: selectedService.iD,
                serviceID: selectedService.serviceID,
                selectedServiceName: selectedService.text,
                selectedServiceNameAR: selectedService.textN,
                price: selectedService.price,
                vAT: selectedService.priceVAT,
                totalPrice: selectedService.priceTotal,
              ),
            ];

            await hmgServicesViewModel.addCmcOrder(
              projectID: selectedHospital.mainProjectID ?? 0,
              orderServiceID: selectedService.orderServiceID ?? 3,
              services: servicesList,
              onSuccess: (requestId) {
                LoaderBottomSheet.hideLoader();
                showSuccessBottomSheet(requestId, hmgServicesViewModel);
              },
              onError: (err) {
                LoaderBottomSheet.hideLoader();
                // showCommonBottomSheetWithoutHeight(context, child: Utils.getErrorWidget(loadingText: err), callBackFunc: () {});
              },
            );
          }),
      callBackFunc: () {},
      isFullScreen: false,
      isCloseButtonVisible: true,
    );
  }
}
