import 'dart:convert';

import 'package:siro_driver/constant/box_name.dart';
import 'package:siro_driver/constant/links.dart';
import 'package:siro_driver/controller/functions/crud.dart';
import 'package:siro_driver/main.dart';
import 'package:siro_driver/views/widgets/error_snakbar.dart';
import 'package:siro_driver/views/widgets/mydialoug.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
// Import url_launcher to open the app store
import 'package:url_launcher/url_launcher.dart';

class RatingController extends GetxController {
  var userRating = 0.obs;
  final comment = TextEditingController();
  void submitRating(int rating) {
    userRating.value = rating;

    _saveRating(rating);
  }

  void _redirectToAppStore() async {
    // URLs for App Store and Google Play Store
    const appStoreUrl =
        'https://apps.apple.com/st/app/siro-driver/id6482995159';
    const playStoreUrl =
        'https://play.google.com/store/apps/details?id=com.siro_driver';
    final url = GetPlatform.isIOS ? appStoreUrl : playStoreUrl;

    if (await launchUrl(Uri.parse(url))) {
      await launchUrl(Uri.parse(url));
    } else {
      mySnackeBarError("Could not open the app store.");
    }
  }

  Future<void> _saveRating(int rating) async {
    // Build the payload with user data
    final payload = {
      "name": box.read(BoxName.driverID) != null
          ? box.read(BoxName.nameDriver)
          : box.read(BoxName.name),
      "email": (box.read(BoxName.emailDriver)).toString(),
      "phone": (box.read(BoxName.phoneDriver)).toString(),
      "userId": box.read(BoxName.driverID),
      "userType": "driver",
      "rating": rating.toString(),
      "comment": comment.text.isEmpty
          ? 'nothing'
          : comment.text, // Get actual text from comment controller
    };

    // Send the rating data to the backend
    var res = await CRUD().post(link: AppLink.addRateApp, payload: payload);

    // Handle the response and check if it's JSON-formatted
    if (res != 'failure') {
      try {
        // Attempt to parse the response as JSON
        final parsedResponse = (res);

        if (parsedResponse['status'] == 'success') {
          // Display a success message
          CRUD().post(link: AppLink.sendEmailRateingApp, payload: {
            "name": payload["name"],
            "email": payload["email"],
            "phone": payload["phone"],
            "rating": rating.toString(),
            "comment": payload["comment"],
          });
          MyDialog().getDialog('Rating submitted successfully'.tr, '', () {
            if (rating == 5) {
              Get.back();
              _redirectToAppStore();
            } else {
              Get.back();
            }
          });

          // Send confirmation email if the rating was successfully submitted
        } else {
          mySnackeBarError('Failed to submit rating');
        }
      } catch (e) {
        // If JSON decoding fails, log the response directly
        // Get.snackbar('Success', 'Rating submitted successfully',
        //     backgroundColor: AppColor.greenColor);
      }
    } else {
      mySnackeBarError('Failed to connect to the server');
    }
  }
}
