import 'dart:io';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:google_api_availability/google_api_availability.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';

class RequestApprovalBottomSheet extends StatefulWidget {
  RequestApprovalBottomSheet({Key? key}) : super(key: key);

  @override
  _RequestApprovalBottomState createState() {
    return _RequestApprovalBottomState();
  }
}

class _RequestApprovalBottomState extends State<RequestApprovalBottomSheet> {
  @override
  void initState() {
    super.initState();
    // listenForApproval();
  }

  void listenForApproval() async {
    print('listen for approval called..');
    if (Platform.isAndroid && !(await isGoogleServicesAvailable())) {
      // h_push.Push.onMessageReceivedStream.listen((h_push.RemoteMessage remoteMessage) {
      //   ConfirmArrivalNotificationModel notificationModel =    ConfirmArrivalNotificationModel.fromJson(remoteMessage.ex);
      //   if(notificationModel.requestId!=null&&notificationModel.accept!=null){
      //     if(notificationModel.accept=='True'){
      //       Navigator.pop(context, true);
      //     }else if(notificationModel.accept=='False'){
      //       Navigator.pop(context, false);
      //     }
      //   }
      // }, onError: (Object error) {
      //   print("onMessageReceivedStream:${error.toString()}");
      // });
    } else {
      FirebaseMessaging.onMessage.listen((RemoteMessage message) {
        ConfirmArrivalNotificationModel notificationModel = ConfirmArrivalNotificationModel.fromJson(message.data);
        if (notificationModel.requestId != null && notificationModel.accept != null) {
          if (notificationModel.accept == 'True') {
            Navigator.pop(context, true);
          } else if (notificationModel.accept == 'False') {
            Navigator.pop(context, false);
          }
        }
        // Map<String, dynamic> messageData = message.data;
        // if (messageData["notificationType"] != null && messageData["accept"] != null) {
        //   if (messageData["notificationType"] == "arrivalConfirmation") {
        //     if ((messageData["accept"].toString()) == "False") {
        //       if(messageData["accept"])
        //       Navigator.pop(context, true);
        //     } else {
        //       Navigator.pop(context, false);
        //     }
        //   }
        // }
      });
    }
  }

  static Future<bool> isGoogleServicesAvailable() async {
    GooglePlayServicesAvailability availability = await GoogleApiAvailability.instance.checkGooglePlayServicesAvailability();
    String status = availability.toString().split('.').last;
    if (status == "success") {
      return true;
    }
    return false;
  }

  @override
  void dispose() {
    print('bottomsheet disposed..');
    // ServiceRequestDetailProvider serviceRequestDetailProvider =Provider.of<ServiceRequestDetailProvider>(context,listen: false);
    // serviceRequestDetailProvider.isVerifyArrivalBottomSheetOpen=false;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      clipBehavior: Clip.antiAlias,
      width: double.infinity,
      margin: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
      decoration: BoxDecoration(
        color: AppColor.background(context),
        borderRadius: const BorderRadius.only(topRight: Radius.circular(20), topLeft: Radius.circular(20)),
      ),
      padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth, vertical: 24.toScreenHeight),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          "Waiting...".heading4(context),
          12.height,
          Text(
            "Request Sent, Waiting for requester to confirm arrival",
            style: TextStyle(
              fontSize: 16.toScreenWidth,
              fontWeight: FontWeight.w500,
              fontStyle: FontStyle.normal,
              decoration: TextDecoration.none,
            ),
          ),
          12.height,
          "waiting".toLottieAsset(height: 100).center,
          12.height,
        ],
      ),
    );
    ;
  }
}

class ConfirmArrivalNotificationModel {
  final String? transactionType;
  final String? requestId;
  final String? notificationType;
  final String? userId;
  final String? accept;

  ConfirmArrivalNotificationModel({
    this.transactionType,
    this.requestId,
    this.notificationType,
    this.userId,
    this.accept,
  });

  // Factory constructor to create an instance from a Map (e.g., JSON)
  factory ConfirmArrivalNotificationModel.fromJson(Map<String, dynamic> json) {
    return ConfirmArrivalNotificationModel(
      transactionType: json['transactionType'],
      requestId: json['requestId'],
      notificationType: json['notificationType'],
      userId: json['userId'],
      accept: json['accept'],
    );
  }

  // Convert an instance to a Map (e.g., for serialization)
  Map<String, dynamic> toJson() {
    return {
      'transactionType': transactionType,
      'requestId': requestId,
      'notificationType': notificationType,
      'userId': userId,
      'accept': accept,
    };
  }
}
