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/location/location_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.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/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 HhcSelectionReviewPage extends StatefulWidget {
  final List<GetCMCServicesResponseModel> selectedServices;

  const HhcSelectionReviewPage({super.key, required this.selectedServices});

  @override
  State<HhcSelectionReviewPage> createState() => _HhcSelectionReviewPageState();
}

class _HhcSelectionReviewPageState extends State<HhcSelectionReviewPage> {
  @override
  void initState() {
    super.initState();
    // Initialize ViewModel state with selected services
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final hmgServicesViewModel = context.read<HmgServicesViewModel>();
      if (widget.selectedServices.isNotEmpty) {
        hmgServicesViewModel.setSelectedServiceForHhcOrder(widget.selectedServices.first);
      }
    });
  }

  @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: [
            _buildSelectedServicesCard(isArabic),
            SizedBox(height: 16.h),
            _buildLocationMap(),
            SizedBox(height: 16.h),
          ],
        ),
      ),
    );
  }

  Widget _buildSelectedServicesCard(bool isArabic) {
    return Container(
      width: double.infinity,
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r),
      padding: EdgeInsets.all(16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          LocaleKeys.selectedServices.tr(context: context).toText14(
                weight: FontWeight.w600,
                color: AppColors.textColor,
                letterSpacing: -0.4,
              ),
          SizedBox(height: 12.h),
          Wrap(
            spacing: 8.w,
            runSpacing: 12.w,
            children: widget.selectedServices.map((service) {
              final serviceName = isArabic ? (service.textN ?? service.text ?? '') : (service.text ?? '');
              return AppCustomChipWidget(labelText: serviceName);
            }).toList(),
          ),
        ],
      ),
    );
  }

  Widget _buildLocationMap() {
    final locationViewModel = getIt.get<LocationViewModel>();
    final geocodeResponse = locationViewModel.geocodeResponse;
    final mapCapturedLocation = locationViewModel.mapCapturedLocation;

    // Check if we have location data
    if (mapCapturedLocation == null || (mapCapturedLocation.lat == 0.0 && mapCapturedLocation.lng == 0.0)) {
      return SizedBox.shrink();
    }

    final double lat = mapCapturedLocation?.lat ?? 0.0;
    final double lng = mapCapturedLocation?.lng ?? 0.0;

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

    // Get address from geocode response
    String address = LocaleKeys.selectLocation.tr(context: context);
    if (geocodeResponse != null && geocodeResponse.results.isNotEmpty) {
      address = geocodeResponse.results.first.formattedAddress;
    }

    return LocationMapWidget(
      latitude: lat,
      longitude: lng,
      address: address,
      onDirectionsTap: () => _launchDirectionsToLocation(lat, lng, address),
    );
  }

  Widget _buildBottomButton() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 24.h),
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.r,
        hasShadow: true,
      ),
      child: CustomButton(
        borderWidth: 0,
        text: LocaleKeys.confirm.tr(context: context),
        onPressed: () => _handleConfirm(),
        textColor: AppColors.whiteColor,
        borderRadius: 12.r,
        borderColor: Colors.transparent,
      ),
    );
  }

  void _launchDirectionsToLocation(double lat, double lng, String locationName) async {
    if (lat != 0.0 && lng != 0.0) {
      await MapLauncher.showMarker(
        mapType: MapType.google,
        coords: Coords(lat, lng),
        title: locationName,
      ).catchError((err) {
        MapLauncher.showMarker(
          mapType: Platform.isIOS ? MapType.apple : MapType.google,
          coords: Coords(lat, lng),
          title: locationName,
        );
      });
    }
  }

  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.getAllHhcOrders();
                    },
                    textColor: AppColors.whiteColor,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
      isCloseButtonVisible: false,
      isDismissible: false,
      isFullScreen: false,
    );
  }

  void _handleConfirm() {
    final hmgServicesViewModel = context.read<HmgServicesViewModel>();
    final appState = getIt.get<AppState>();

    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 from all selected services
            final servicesList = widget.selectedServices.map((selectedService) {
              return PatientERCMCInsertServicesList(
                recordID: selectedService.iD,
                serviceID: selectedService.serviceID,
                selectedServiceName: selectedService.text,
                selectedServiceNameAR: selectedService.textN,
                price: selectedService.price,
                vAT: selectedService.priceVAT,
                totalPrice: selectedService.priceTotal,
              );
            }).toList();

            // For HHC, we don't need hospital selection, use a default projectID or 0
            await hmgServicesViewModel.addHhcOrder(
              projectID: 0,
              // HHC doesn't require hospital/project selection
              orderServiceID: widget.selectedServices.first.orderServiceID ?? 4,
              // HHC service ID
              services: servicesList,
              onSuccess: (requestId) {
                LoaderBottomSheet.hideLoader();
                showSuccessBottomSheet(requestId, hmgServicesViewModel);
              },
              onError: (err) {
                LoaderBottomSheet.hideLoader();
              },
            );
          }),
      callBackFunc: () {},
      isFullScreen: false,
      isCloseButtonVisible: true,
    );
  }
}
