import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:siro_driver/constant/links.dart';
import 'package:siro_driver/controller/functions/crud.dart';
import 'package:siro_driver/views/widgets/error_snakbar.dart';

import '../../views/widgets/mycircular.dart';

class InvitesRewardsController extends GetxController {
  bool isLoading = false;
  String? referralCode;
  int totalInvitedDrivers = 0;
  int totalInvitedPassengers = 0;
  List<dynamic> referrals = [];

  @override
  void onInit() {
    super.onInit();
    getReferralStats();
  }

  Future<void> getReferralStats() async {
    isLoading = true;
    update();

    var res = await CRUD().get(link: AppLink.getDriverReferrals);

    if (res != 'failure' && res != 'token_expired' && res != 'no_internet') {
      try {
        var jsonData = jsonDecode(res);
        if (jsonData['status'] == 'success') {
          var data = jsonData['message'];
          referralCode = data['referral_code'];
          totalInvitedDrivers = data['total_invited_drivers'] ?? 0;
          totalInvitedPassengers = data['total_invited_passengers'] ?? 0;
          referrals = data['referrals'] ?? [];
        }
      } catch (e) {
        debugPrint('Error parsing referral stats: $e');
      }
    }

    isLoading = false;
    update();
  }

  Future<void> claimReward(int referralId, String claimType) async {
    Get.dialog(const Center(child: CircularProgressIndicator()),
        barrierDismissible: false);

    var res = await CRUD().post(
      link: AppLink.claimDriverReward,
      payload: {
        'referral_id': referralId.toString(),
        'claim_type': claimType, // 'wallet' or 'cash'
      },
    );

    Get.back(); // close dialog

    if (res != 'failure' && res != 'token_expired' && res != 'no_internet') {
      try {
        var jsonData = jsonDecode(res);
        if (jsonData['status'] == 'success') {
          mySnackbarSuccess('Reward claimed successfully!'.tr);
          await getReferralStats(); // refresh list
        } else {
          mySnackeBarError(jsonData['error'] ?? 'Failed to claim reward'.tr);
        }
      } catch (e) {
        mySnackeBarError('Failed to claim reward'.tr);
      }
    } else {
      mySnackeBarError('Connection error'.tr);
    }
  }

  Future<void> claimUnifiedReward(int referralId) async {
    // Show dialog to choose wallet or cash
    Get.defaultDialog(
        title: "Choose Claim Method".tr,
        content: Text("How would you like to receive your reward?".tr),
        actions: [
          ElevatedButton(
            onPressed: () {
              Get.back();
              claimReward(referralId, 'wallet');
            },
            child: Text("Wallet".tr),
          ),
          ElevatedButton(
            onPressed: () {
              Get.back();
              claimReward(referralId, 'cash');
            },
            child: Text("Cash".tr),
          ),
          TextButton(
            onPressed: () => Get.back(),
            child: Text("Cancel".tr, style: TextStyle(color: Colors.red)),
          )
        ]);
  }

  Future<void> linkInviteCode(String inviteCode) async {
    Get.dialog(const Center(child: MyCircularProgressIndicator()),
        barrierDismissible: false);

    try {
      var response =
          await CRUD().post(link: AppLink.addUnifiedInvite, payload: {
        "inviter_code": inviteCode,
      });

      Get.back(); // close loading

      if (response != 'failure') {
        var data = response is String ? jsonDecode(response) : response;
        if (data['status'] == 'success') {
          Get.snackbar("Success".tr, "You have been successfully referred!".tr,
              backgroundColor: Colors.green, colorText: Colors.white);
          await getReferralStats(); // Refresh stats
        } else {
          Get.snackbar(
              "Notice".tr, data['message'] ?? "Could not add invite".tr);
        }
      } else {
        Get.snackbar("Error".tr, "Network error occurred".tr);
      }
    } catch (e) {
      Get.back(); // close loading
      Get.snackbar("Error".tr, "Network error occurred".tr);
    }
  }
}
