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/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/emergency_services/emergency_services_view_model.dart';
import 'package:hmg_patient_app_new/features/emergency_services/models/resp_model/AmbulanceRequestOrdersModel.dart';
import 'package:hmg_patient_app_new/features/emergency_services/models/resp_model/RRTServiceData.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/map/HMSMap.dart';
import 'package:hmg_patient_app_new/widgets/map/gms_map.dart' show GMSMap;
import 'package:hmg_patient_app_new/widgets/order_tracking/order_tracking_state.dart';
import 'package:hmg_patient_app_new/widgets/order_tracking/request_tracking.dart';
import 'package:lottie/lottie.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart' show launchUrl;

class TrackingScreen extends StatelessWidget {
  OrderTrackingState? state ;
  final bool isRRTOrder;
  final AmbulanceRequestOrdersModel? order;
  final GetCMCAllOrdersResponseModel? rrtOrder;

  TrackingScreen({super.key, OrderTrackingState? state, this.order, this.isRRTOrder = false, this.rrtOrder}){
    if(state == null){
      switch (order?.statusId ?? rrtOrder?.statusId) {
        case 1: //pending
        case 2: //processing
          this.state = OrderTrackingState.waitingForCall;
          break;
        case 3: //completed
          this.state = OrderTrackingState.dispactched;
          break;
        case 4: //cancel
        case 6:
        case 7:
          this.state = OrderTrackingState.cancel;
          break;
      }

    }else {
      this.state = state;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: Visibility(
        visible: state == OrderTrackingState.ended,
        child: SafeArea(
          child: CustomButton(
            height: 40.h,
            iconSize: 18.w,
            backgroundColor: AppColors.bgGreenColor,
            borderColor: Colors.transparent,
            text: LocaleKeys.close.tr(context: context),
            textColor: AppColors.whiteColor,
            onPressed: () {},
          ).paddingOnly(left: 16.h, right: 16.h),
        ),
      ),
      body: CollapsingListView(
          title: LocaleKeys.trackingDetails.tr(context: context),
          child: SingleChildScrollView(
              child: Column(
            children: [
              Padding(
                padding: EdgeInsetsDirectional.only(top:16.h,start: 16.w,end: 16.w ),
                child: animationSection(context),
              ),
              Column(
                spacing: 16.h,
                children: [orderStatus(context), orderTrackingId(context), contactSection()],
              ).paddingAll(16.h),
            ],
          ))),
    );
  }

  animationSection(BuildContext context) {
    switch (state) {
      case OrderTrackingState.waitingForCall:
      case OrderTrackingState.dispactched:
      case OrderTrackingState.returning:
        return showImage(order != null ? AppAssets.ambulance_section : AppAssets.rrt_section, context);
      case OrderTrackingState.ended:
        return Lottie.asset(AppAnimations.checkmark, repeat: true, width: 260.h, height: 200.h);
      case OrderTrackingState.failed:
      case OrderTrackingState.cancel:
      case null:
        return Lottie.asset(AppAnimations.errorAnimation, repeat: true, width: 260.h, height: 200.h);
    }
  }

  orderStatus(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(16.h),
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 20.h,
        hasShadow: false,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          getTitle(state),
          SizedBox(height: 12.h),
          OrderTrackingWidget(
            height: 6.h,
            state: state,
            parentPaddingValue: 16.h,
          ),
          SizedBox(height: 24.h),
          informationRegardingTrackingSection(),
          trackingBottomSection(context)
        ],
      ),
    );
  }

  Widget trackingBottomSection(BuildContext context) {
    if(state == null )
      {
        return SizedBox.shrink();
      }
    switch (state!) {
      case OrderTrackingState.waitingForCall:
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(
              height: 16,
            ),
            CustomButton(
              text: LocaleKeys.cancelRequest.tr(context: context),
              onPressed: () async {
                openCancelOrderBottomSheet(context);
              },
              backgroundColor: AppColors.primaryRedColor,
              borderColor: AppColors.primaryRedColor,
              textColor: Colors.white,
              icon: AppAssets.cancel,
              height: 56.h,
              iconSize: 18.w,
            ),
          ],
        );
      case OrderTrackingState.dispactched:
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          spacing: 12.h,
          children: [
            dividerSection,
            doctorSection(),
            mapSection(context),
            CustomButton(
              height: 40.h,
              iconSize: 18.w,
              backgroundColor: AppColors.lightRedButtonColor,
              borderColor: Colors.transparent,
              text: LocaleKeys.shareLocationWhatsapp.tr(context: context),
              fontSize: 12.f,
              textColor: AppColors.primaryRedColor,
              iconColor: AppColors.primaryRedColor,
              onPressed: () {},
              icon: AppAssets.share_location,
            ),
          ],
        );
      case OrderTrackingState.returning:
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          spacing: 12.h,
          children: [dividerSection, doctorSection(), mapSection(context)],
        );
      case OrderTrackingState.ended:
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          spacing: 12.h,
          children: [
            dividerSection,
            doctorSection(),
          ],
        );
      case OrderTrackingState.failed:
      case OrderTrackingState.cancel:
        return SizedBox.shrink();

    }
  }

  Widget get dividerSection => Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            height: 16,
          ),
          Divider(
            thickness: 1.5.h,
            color: AppColors.borderGrayColor,
          ),
          SizedBox(
            height: 4,
          )
        ],
      );

  doctorSection() {
    return Row(
      spacing: 16.h,
      children: [
        Utils.buildImgWithNetwork(url: "", iconColor: Colors.transparent).circle(52.h),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              "Dr. John Doe".toText16(color: AppColors.textColor, isBold: true),
              SizedBox(height: 4.h),
              "MBBS, MD - General Medicine".toText12(color: AppColors.greyTextColor, isBold: true),
            ],
          ),
        ),
        SizedBox(
          height: 36.h,
          width: 36.h,
          child: CustomButton(
            text: '',
            iconSize: 18.h,
            icon: AppAssets.call_fill,
            onPressed: () {},
            backgroundColor: AppColors.lightRedButtonColor,
            iconColor: AppColors.primaryRedColor,
            borderColor: Colors.transparent,
            height: 56.h,
          ),
        )
      ],
    );
  }

  Widget mapForRequestedCoordinate(BuildContext context) {
    // return SizedBox.shrink();
    if (context.read<EmergencyServicesViewModel>().isGMSAvailable || Platform.isIOS) {
      return GMSMap(
          myLocationEnabled: false,
          onCameraIdle: (){

          },
          currentLocation: context.read<EmergencyServicesViewModel>().getGMSLocation(),
        onCameraMoved: (value) => context.read<EmergencyServicesViewModel>().handleGMSMapCameraMoved(value),
        bottomPaddingHeight: MediaQuery.of(context).size.height * 0.2,
      );
    } else {
      return HMSMap(
          myLocationEnabled: false,
          onCameraIdle: (){

          },
          currentLocation: context.read<EmergencyServicesViewModel>().getHMSLocation(),
          onCameraMoved: (value) => context.read<EmergencyServicesViewModel>().handleHMSMapCameraMoved(value));
    }
  }

  informationRegardingTrackingSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [currentStatus(), SizedBox(height: 4.h)],
    );
  }

  currentStatus() {
    if(state == null){
      return SizedBox.shrink();
    }
    switch (state!) {
      case OrderTrackingState.waitingForCall:
      case OrderTrackingState.dispactched:
        return RichText(
          text: TextSpan(children: <TextSpan>[
            TextSpan(
              text: LocaleKeys.pleaseWaitForCall.tr(),
              style: TextStyle(
                fontSize: 21.f,
                fontWeight: FontWeight.w600,
               color: AppColors.textColor,
             ),
           ),
           TextSpan(
             text: "...",
             style: TextStyle(
                fontSize: 21.f,
               fontWeight: FontWeight.w600,
               color: AppColors.errorColor,
             ),
           ),
         ]),
       );
     case OrderTrackingState.returning:
       return RichText(
         text: TextSpan(children: <TextSpan>[
           TextSpan(
             text: "15:30",
             style: TextStyle(
                fontSize: 21.f,
               fontWeight: FontWeight.w600,
               color: AppColors.textColor,
             ),
           ),
           TextSpan(
             text: LocaleKeys.mins.tr(),
             style: TextStyle(
                fontSize: 21.f,
               fontWeight: FontWeight.w600,
               color: AppColors.errorColor,
             ),
           ),
           TextSpan(
             text: LocaleKeys.toHospitalLower.tr(),
             style: TextStyle(
                fontSize: 21.f,
               fontWeight: FontWeight.w600,
               color: AppColors.textColor,
             ),
           ),
         ]),
       );
     case OrderTrackingState.ended:

        return LocaleKeys.arrived.tr().toText21(color: AppColors.textColor, isBold: true);
      case OrderTrackingState.failed:
      case OrderTrackingState.cancel:
       return SizedBox.shrink();
    }
  }

  orderTrackingId(BuildContext context) {
    if(state == OrderTrackingState.failed){
      return SizedBox.shrink();
    }
    return Container(
      width: MediaQuery.sizeOf(context).width-32.h,
      padding: EdgeInsets.all(16.h),
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 20.h,
        hasShadow: false,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        spacing: 8.h,
        children: [

          Visibility(visible:(order != null || rrtOrder != null)  ,child: "Req ID: ${order?.iD?? rrtOrder?.iD}".toText16(color: AppColors.textColor, isBold: true)),
          if(order != null) ambulanceOrderData()
          // else rrtOrderData()

        ],
      ),
    );
  }

  chip(String title, String iconString, Color iconColor) {
    return AppCustomChipWidget(
      labelText: title,
      icon: iconString,
      iconColor: iconColor,
      iconSize: 14.h,
    );
  }

  contactSection() {
    if(isRRTOrder) return SizedBox.shrink();
    return Container(
      padding: EdgeInsets.all(16.h),
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 20.h,
        hasShadow: false,
      ),
      child: Row(
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              spacing: 4.h,
              children: [
                LocaleKeys.contact.tr().toText14(color: AppColors.textColor, isBold: true),
                "0115259555".toText12(color: AppColors.primaryRedColor, isBold: true).onPress((){
                  launchUrl(
                    Uri.parse("tel://0115259555"),
                  );
                }),
                SizedBox(height: 8.h),
              ],
            ),
          ),
          SizedBox(
            height: 36.h,
            width: 36.h,
            child: CustomButton(
              text: '',
              iconSize: 16.h,
              icon: AppAssets.call_fill,
              onPressed: () {},
              backgroundColor: AppColors.lightRedButtonColor,
              iconColor: AppColors.primaryRedColor,
              borderColor: Colors.transparent,
              height: 36.h,
            ),
          ).onPress((){
            launchUrl(
              Uri.parse("tel://0115259555"),
            );
          })
        ],
      ),
    );
  }

  //  "c": {
  //                 "a": 0,
  //                 "k": [
  //                   1,
  //                   1,
  //                   1
  //                 ]
  //               }

  getTitle(OrderTrackingState? state) {
    if(state == null) {
      return LocaleKeys.failed.tr().toText16(color: AppColors.textColor, isBold: true);
    }

    switch (state) {
      case OrderTrackingState.waitingForCall:
        return LocaleKeys.confirmationCall.tr().toText16(color: AppColors.textColor, isBold: true);
      case OrderTrackingState.dispactched:
        return LocaleKeys.pickupFromHome.tr().toText16(color: AppColors.textColor, isBold: true);
      case OrderTrackingState.returning:
        return LocaleKeys.onTheWayToHospital.tr().toText16(color: AppColors.textColor, isBold: true);
      case OrderTrackingState.ended:
        return LocaleKeys.arrivedAtHospital.tr().toText16(color: AppColors.textColor, isBold: true);
      case OrderTrackingState.failed:
        return LocaleKeys.failed.tr().toText16(color: AppColors.textColor, isBold: true);

      case OrderTrackingState.cancel:
        return LocaleKeys.orderCancel.tr().toText16(color: AppColors.textColor, isBold: true);
    }
  }

  mapSection(BuildContext context) {
    return SizedBox(
      height: 170.h,
      width: double.infinity,
      child: ClipRRect(borderRadius: BorderRadius.circular(20.h), child: mapForRequestedCoordinate(context)),
    );
  }


  openCancelOrderBottomSheet(BuildContext context){
    if(isRRTOrder){
      context.read<EmergencyServicesViewModel>().cancelRRTOrder(rrtOrder?.iD??-1, shouldPop:  true);
      return;
    }else {
      context.read<EmergencyServicesViewModel>().cancelOrder(order, shouldPop:  true);
      return;
    }
  }

  Widget ambulanceOrderData() {
    return  Row(
      spacing: 8.h,
      children: [
        Flexible(child:
        chip(order?.pickupLocation??"", AppAssets.location_pickup, AppColors.blackBgColor),

        ),
        Flexible(child:
        chip(order?.dropOffLocation??"", AppAssets.hospital, AppColors.blackBgColor),

        )
      ],
    );
  }

  showImage(String imageUrl, BuildContext context) {
    return Utils.buildImgWithAssetsWithBorderRadius(
      icon: imageUrl,
      iconColor: Colors.transparent,
      width: MediaQuery.sizeOf(context).width,
      height: 380.h,
      borderRadius: 24.r,
      border: 1.r/// did this as the function that is being called is wrongly coupled with the border radius and border, and in some cases like the ambulance and rrt section we don't need any
      /// border or border radius
    );
  }

  //   Widget rrtOrderData() {
  //   return  Row(
  //     spacing: 8.h,
  //     children: [
  //       Flexible(child:
  //       chip(rrtOrder?.pickupLocation??"", AppAssets.location_pickup, AppColors.blackBgColor),
  //
  //       ),
  //       // Flexible(child:
  //       // chip(rrtOrder?.??"", AppAssets.hospital, AppColors.blackBgColor),
  //       //
  //       // )
  //     ],
  //   );
  // }
}
