import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:test_sa/controllers/api_routes/api_manager.dart';
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/modules/applicationDemo/models/application_demo_request_model.dart';
import 'package:test_sa/modules/applicationDemo/models/role_model.dart';
import 'dart:convert';

class ApplicationDemoRequestProvider extends ChangeNotifier {
  bool _loading = false;
  bool _roleLoading = false;
  List<ApplicationDemoRoleModel> _roles = [];
  String? _errorMessage;
  String? _successMessage;

  bool get loading => _loading;

  bool get roleLoading => _roleLoading;

  String? get errorMessage => _errorMessage;

  String? get successMessage => _successMessage;

  List<ApplicationDemoRoleModel> get roles => _roles;

  set loading(bool value) {
    _loading = value;
    notifyListeners();
  }

  set roleLoading(bool value) {
    _loading = value;
    notifyListeners();
  }

  Map<String, String> get _unauthenticatedHeaders => {
        'Content-Type': 'application/json',
        'X-Timezone-Offset': DateTime.now().timeZoneOffset.toString().split(".").first,
      };

  Future<int> fetchRoles({String? searchText}) async {
    if (roleLoading) return -2;
    roleLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      final response = await ApiManager.instance.post(URLs.getApplicationDemoRoles, headers: _unauthenticatedHeaders, body: {'searchText': searchText ?? ''});

      if (response.statusCode >= 200 && response.statusCode < 300) {
        final Map<String, dynamic> responseData = jsonDecode(response.body);
        List<dynamic> rolesList = [];
        if (responseData.containsKey('data')) {
          rolesList = responseData['data'] is List ? responseData['data'] : [];
        } else if (responseData.containsKey('roles')) {
          rolesList = responseData['roles'] is List ? responseData['roles'] : [];
        }

        _roles = rolesList.map((json) => ApplicationDemoRoleModel.fromJson(json)).toList();

        roleLoading = false;
        notifyListeners();
        return response.statusCode;
      } else {
        final responseData = jsonDecode(response.body);
        _errorMessage = responseData['message'] ?? 'Failed to fetch roles';
        roleLoading = false;
        notifyListeners();
        return response.statusCode;
      }
    } catch (error) {
      _errorMessage = 'Failed to fetch roles: $error';
      roleLoading = false;
      notifyListeners();
      return -1;
    }
  }

  /// Submits an application demo request to the server (without authentication)
  Future<bool> submitApplicationDemoRequest(ApplicationDemoRequestModel request) async {
    loading = true;
    _errorMessage = null;
    _successMessage = null;
    notifyListeners();

    try {
      final requestBody = request.toJson();

      final response = await ApiManager.instance.post(
        URLs.submitApplicationDemoRequest,
        headers: _unauthenticatedHeaders,
        body: requestBody,
      );

      if (response.statusCode >= 200 && response.statusCode < 300) {
        final responseData = json.decode(response.body);
        _successMessage = responseData['message'] ?? 'Your demo request has been submitted successfully';
        loading = false;
        notifyListeners();
        return true;
      } else {
        final responseData = json.decode(response.body);
        _errorMessage = responseData['message'] ?? 'Failed to submit request';
        loading = false;
        notifyListeners();
        return false;
      }
    } catch (error) {
      _errorMessage = 'Failed to submit request: $error';
      loading = false;
      notifyListeners();
      return false;
    }
  }

  /// Sends OTP to user via email or SMS
  Future<bool> sendOtp({
    required String fullName,
    required String phoneNumber,
    required String email,
    required String typeSend, // "SMS" or "Email"
  }) async {
    loading = true;
    _errorMessage = null;
    _successMessage = null;
    notifyListeners();

    try {
      final requestBody = {
        'fullName': fullName,
        'phoneNumber': phoneNumber,
        'email': email,
        'typeSend': typeSend,
      };

      final response = await ApiManager.instance.post(
        URLs.sendDemoUserOtp,
        headers: _unauthenticatedHeaders,
        body: requestBody,
      );

      if (response.statusCode >= 200 && response.statusCode < 300) {
        final responseData = json.decode(response.body);
        _successMessage = responseData['message'];
        loading = false;
        notifyListeners();
        return true;
      } else {
        final responseData = json.decode(response.body);
        _errorMessage = responseData['message'] ?? 'Failed to send OTP';
        loading = false;
        notifyListeners();
        return false;
      }
    } catch (error) {
      _errorMessage = 'Failed to send OTP: $error';
      loading = false;
      notifyListeners();
      return false;
    }
  }

  /// Verifies OTP code
  Future<bool> verifyOtp({
    String? email,
    String? phoneNumber,
    required String otpCode,
  }) async {
    loading = true;
    _errorMessage = null;
    _successMessage = null;
    notifyListeners();

    try {
      final requestBody = <String, dynamic>{
        'otpCode': otpCode,
      };

      // Add email or phoneNumber based on what's provided
      if (email != null && email.isNotEmpty) {
        requestBody['email'] = email;
      }
      if (phoneNumber != null && phoneNumber.isNotEmpty) {
        requestBody['phoneNumber'] = phoneNumber;
      }

      final response = await ApiManager.instance.post(
        URLs.verifyDemoUserOtp,
        headers: _unauthenticatedHeaders,
        body: requestBody,
      );

      if (response.statusCode >= 200 && response.statusCode < 300) {
        final responseData = json.decode(response.body);
        _successMessage = responseData['message'];
        loading = false;
        notifyListeners();
        return true;
      } else {
        final responseData = json.decode(response.body);
        _errorMessage = responseData['message'] ?? 'Invalid OTP code';
        loading = false;
        notifyListeners();
        return false;
      }
    } catch (error) {
      _errorMessage = 'Failed to verify OTP: $error';
      loading = false;
      notifyListeners();
      return false;
    }
  }

  /// Resets the provider state
  void reset() {
    _loading = false;
    _roles.clear();
    _errorMessage = null;
    notifyListeners();
  }
}
