import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:test_sa/controllers/api_routes/api_manager.dart';
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/modules/signup/models/employee_erp_model.dart';
import 'package:test_sa/modules/signup/models/signup_request_model.dart';
import 'package:test_sa/modules/signup/models/site_model.dart';
import 'package:test_sa/modules/signup/models/department_model.dart';

class SignUpProvider extends ChangeNotifier {
  bool _loading = false;

  bool get loading => _loading;

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

  EmployeeERPModel? _employeeData;

  EmployeeERPModel? get employeeData => _employeeData;

  List<SiteModel> _sites = [];

  List<SiteModel> get sites => _sites;

  List<DepartmentModel> _departments = [];

  List<DepartmentModel> get departments => _departments;

  String? _errorMessage;

  String? get errorMessage => _errorMessage;

  String? _successMessage;

  String? get successMessage => _successMessage;

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

  /// Fetch employee details from ERP
  Future<EmployeeERPModel?> getEmployeeFromERP(String employeeId) async {
    if (loading) return null;

    loading = true;
    _errorMessage = null;
    _employeeData = null;
    notifyListeners();

    try {
      final url = '${URLs.signUpGetEmployeeFromERP}?employeeId=$employeeId';
      final response = await ApiManager.instance.get(url, headers: _unauthenticatedHeaders);

      if (response.statusCode >= 200 && response.statusCode < 300) {
        final data = json.decode(response.body);

        // Check if data is null (employee not found case)
        if (data['data'] == null) {
          _errorMessage = data['message'];
          loading = false;
          notifyListeners();
          return null;
        }

        _employeeData = EmployeeERPModel.fromJson(data['data']);

        loading = false;
        notifyListeners();
        return _employeeData;
      } else {
        final data = json.decode(response.body);
        _errorMessage = data['message'];
        loading = false;
        notifyListeners();
        return null;
      }
    } catch (error) {
      _errorMessage = error.toString();
      loading = false;
      notifyListeners();
      return null;
    }
  }

  /// Submit signup request
  Future<bool> submitSignUpRequest(SignUpRequestModel request) async {
    if (loading) return false;

    loading = true;
    _errorMessage = null;
    _successMessage = null;
    notifyListeners();

    try {
      final response = await ApiManager.instance.post(URLs.createSignUpRequest, headers: _unauthenticatedHeaders, body: request.toJson(), showToast: false);

      if (response.statusCode >= 200 && response.statusCode < 300) {
        final data = json.decode(response.body);
        _successMessage = data['message'];
        loading = false;
        notifyListeners();
        return true;
      } else {
        final data = json.decode(response.body);
        _errorMessage = data['message'];
        loading = false;
        notifyListeners();
        return false;
      }
    } catch (error) {
      _errorMessage = error.toString();
      loading = false;
      notifyListeners();
      return false;
    }
  }

  /// Fetch site list by asset group
  Future<List<SiteModel>> getSiteList(int assetGroupId) async {
    loading = true;
    _errorMessage = null;
    _sites = [];
    notifyListeners();

    try {
      final url = '${URLs.signUpGetSiteList}?assetGroupId=$assetGroupId';
      final response = await ApiManager.instance.get(
        url,
        headers: _unauthenticatedHeaders,
      );

      if (response.statusCode >= 200 && response.statusCode < 300) {
        final data = json.decode(response.body);
        if (data['data'] != null && data['data'] is List) {
          _sites = (data['data'] as List).map((site) => SiteModel.fromJson(site)).toList();
        }
        loading = false;
        notifyListeners();
        return _sites;
      } else {
        final data = json.decode(response.body);
        _errorMessage = data['message'];
        loading = false;
        notifyListeners();
        return [];
      }
    } catch (error) {
      _errorMessage = error.toString();
      loading = false;
      notifyListeners();
      return [];
    }
  }

  /// Fetch department autocomplete by asset group
  Future<List<DepartmentModel>> getDepartmentAutoComplete(int assetGroupId) async {
    loading = true;
    _errorMessage = null;
    _departments = [];
    notifyListeners();

    try {
      final url = '${URLs.signUpGetDepartmentAutoComplete}?assetGroupId=$assetGroupId';
      final response = await ApiManager.instance.get(
        url,
        headers: _unauthenticatedHeaders,
      );

      if (response.statusCode >= 200 && response.statusCode < 300) {
        final data = json.decode(response.body);
        // The response is directly an array, not wrapped in a data object
        if (data is List) {
          _departments = data.map((dept) => DepartmentModel.fromJson(dept)).toList();
        }
        loading = false;
        notifyListeners();
        return _departments;
      } else {
        final data = json.decode(response.body);
        _errorMessage = data['message'];
        loading = false;
        notifyListeners();
        return [];
      }
    } catch (error) {
      _errorMessage = error.toString();
      loading = false;
      notifyListeners();
      return [];
    }
  }

  void reset() {
    _loading = false;
    _employeeData = null;
    _sites = [];
    _departments = [];
    _errorMessage = null;
    _successMessage = null;
    notifyListeners();
  }
}
