import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:siro_driver/constant/box_name.dart';
import 'package:siro_driver/constant/links.dart';
import 'package:siro_driver/controller/functions/crud.dart';
import '../../main.dart';

class LeaderboardEntry {
  final String driverId;
  final String name;
  final String photoUrl;
  final int rank;
  final double value; // trips or earnings
  final bool isCurrentUser;

  LeaderboardEntry(
      {required this.driverId,
      required this.name,
      required this.photoUrl,
      required this.rank,
      required this.value,
      this.isCurrentUser = false});
}

class LeaderboardController extends GetxController {
  bool isLoading = false;
  int selectedTab = 0; // 0=trips, 1=earnings
  List<LeaderboardEntry> tripLeaderboard = [];
  List<LeaderboardEntry> earningsLeaderboard = [];
  int myRank = 0;

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

  void changeTab(int tab) {
    selectedTab = tab;
    update();
  }

  List<LeaderboardEntry> get currentLeaderboard =>
      selectedTab == 0 ? tripLeaderboard : earningsLeaderboard;
  Future<void> fetchLeaderboard() async {
    isLoading = true;
    update();

    try {
      final myId = box.read(BoxName.driverID)?.toString() ?? '';

      // Fetch trips leaderboard
      var resTrips = await CRUD().post(
        link: AppLink.getLeaderboard,
        payload: {'type': 'trips'},
      );
      if (resTrips != null && resTrips != 'failure') {
        var data = jsonDecode(resTrips);
        if (data['message'] is List) {
          tripLeaderboard = (data['message'] as List).map((e) => LeaderboardEntry(
            driverId: e['driver_id'].toString(),
            name: e['name'].toString(),
            photoUrl: e['photoUrl']?.toString() ?? '',
            rank: int.tryParse(e['rank']?.toString() ?? '0') ?? 0,
            value: double.tryParse(e['value']?.toString() ?? '0') ?? 0,
            isCurrentUser: e['driver_id'].toString() == myId,
          )).toList();
        }
      }

      // Fetch earnings leaderboard
      var resEarnings = await CRUD().post(
        link: AppLink.getLeaderboard,
        payload: {'type': 'earnings'},
      );
      if (resEarnings != null && resEarnings != 'failure') {
        var data = jsonDecode(resEarnings);
        if (data['message'] is List) {
          earningsLeaderboard = (data['message'] as List).map((e) => LeaderboardEntry(
            driverId: e['driver_id'].toString(),
            name: e['name'].toString(),
            photoUrl: e['photoUrl']?.toString() ?? '',
            rank: int.tryParse(e['rank']?.toString() ?? '0') ?? 0,
            value: double.tryParse(e['value']?.toString() ?? '0') ?? 0,
            isCurrentUser: e['driver_id'].toString() == myId,
          )).toList();
        }
      }

      // Find my rank
      final myTripEntry = tripLeaderboard.firstWhereOrNull((e) => e.isCurrentUser);
      final myEarnEntry = earningsLeaderboard.firstWhereOrNull((e) => e.isCurrentUser);
      myRank = selectedTab == 0 ? (myTripEntry?.rank ?? 0) : (myEarnEntry?.rank ?? 0);
    } catch (e) {
      debugPrint('❌ [Leaderboard] Error: $e');
    }

    isLoading = false;
    update();
  }
}
