import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:siro_admin/constant/links.dart';
import 'package:siro_admin/controller/functions/crud.dart';
import 'package:siro_admin/controller/auth/otp_helper.dart';

import '../../constant/box_name.dart';
import '../../main.dart';

class DashboardController extends GetxController {
  bool isLoading = false;
  List dashbord = [];
  String creditSMS = '0';
  final formKey = GlobalKey<FormState>();
  final smsText = TextEditingController();

  Future getDashBoard() async {
    isLoading = true;
    update();

    // 🔹 Request main dashboard data
    var res = await CRUD().get(link: AppLink.getdashbord, payload: {});
    print('📡 Main dashboard response: $res');

    if (res == 'token_expired') {
      print('❌ Admin token expired. Attempting seamless auto-login.');
      box.remove(BoxName.jwt);
      try {
        final otpHelper = Get.put(OtpHelper());
        await otpHelper.checkAdminLogin();
      } catch (e) {
        Get.offAllNamed('/login');
      }
      return;
    }

    if (res != 'failure' && res != null) {
      try {
        var d = res is String ? jsonDecode(res) : res;
        print('✅ Decoded main dashboard: ${jsonEncode(d)}');
        if (d['status'] == 'success' && d['message'] != null) {
          dashbord = d['message'] is List ? d['message'] : [d['message']];
        }
      } catch (e) {
        print('❌ Error parsing main dashboard: $e');
      }
    } else {
      print('❌ Failed to load main dashboard');
    }

    // 🔹 Request wallet dashboard data
    var resPayments = await CRUD().postWallet(
      link: AppLink.getPaymentsDashboard,
      payload: {},
    );
    print('💳 Wallet dashboard response: $resPayments');

    if (resPayments is Map && resPayments['status'] == 'success') {
      var p = resPayments;
      print('✅ Decoded wallet dashboard: ${jsonEncode(p)}');

      if (dashbord.isNotEmpty &&
          p['message'] is List &&
          p['message'].isNotEmpty) {
        dashbord[0].addAll(p['message'][0]);
      } else if (dashbord.isNotEmpty && p['message'] is Map) {
        dashbord[0].addAll(p['message']);
      }
    } else {
      print('❌ Failed to load wallet dashboard (or verification required)');
    }

    // 🔹 Check SMS credit
    // var res2 = await CRUD().kazumiSMS(
    //   link: 'https://sms.kazumi.me/api/sms/check-credit',
    //   payload: {"username": "Sefer", "password": AK.smsPasswordEgypt},
    // );

    // creditSMS = res2['credit'];
    // print('📱 SMS Credit Response: ${jsonEncode(res2)}');
    // print('💰 creditSMS: $creditSMS');

    isLoading = false;
    update();
  }

  sendSMSMethod() async {
    if (formKey.currentState!.validate()) {
      for (var phoneNumber in box.read(BoxName.tokensDrivers)['message']) {
        // for (var i = 0; i < 2; i++) {
        await CRUD().sendSmsEgypt(
          phoneNumber['phone'].toString(),
          // box.read(BoxName.tokensDrivers)['message'][i]['phone'].toString(),
          smsText.text,
        );
        // print('CRUD().phoneDriversTest.: ${phoneNumber['phone']}');
        Future.delayed(const Duration(microseconds: 20));
      }
      Get.back();
    }
  }

  @override
  void onInit() async {
    getDashBoard();

    super.onInit();
  }
}
