import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';

import '../data/api_response.dart';
import '../data/session/session_storage.dart';
import '../services/base_service.dart';
import '../models/models.dart';
import '../services/services.dart';
import '../services/repo_service.dart';

class PermisoViewModel extends ChangeNotifier {
  List<Permiso> _permisos = [];
  bool _isLoading = false;
  Permiso? _selectedPermiso;

  String _busqueda = "";
  String get busqueda => _busqueda;

  List<Permiso> get permisos => _permisos;
  bool get isLoading => _isLoading;

  int _currentPage = 1;
  int _totalPermisos = 0;
  int _limit = 10;

  int get currentPage => _currentPage;
  int get totalPermisos => _totalPermisos;
  int get totalPages => (_totalPermisos / _limit).ceil();

  List<String> _userPermisos = [];
  List<String> get userPermisos => _userPermisos;

  setBusqueda(String value) {
    _busqueda = value;
    notifyListeners();
  }

  void selectPermiso(Permiso permiso) {
    _selectedPermiso = permiso;
    notifyListeners();
  }

  Future<void> fetchLocalAll({int page = 1}) async {
    _currentPage = page;
    var db = await RepoService().db;

    int? count = Sqflite.firstIntValue(
        await db!.rawQuery('SELECT COUNT(*) FROM Permiso'));
    _totalPermisos = count ?? 0;

    int offset = (_limit * (page - 1));

    var query = await db.query('Permiso',
        orderBy: 'id asc', limit: _limit, offset: offset);
    _permisos = query.map((element) => Permiso.fromJson(element)).toList();
    notifyListeners();
  }

  Future<void> sincronizarPermisos() async {
    _isLoading = true;
    notifyListeners();
    try {
      final response = ApiResponse(await BaseService().get('/pos/permiso'));
      if (response.isOk && response.resultados != null) {
        _permisos =
            response.resultados!.map((json) => Permiso.fromJson(json)).toList();
        await RepoService().sincronizarPermisos(_permisos);
      }
    } catch (e) {
      print('Error fetching permisos: $e');
    }
    _isLoading = false;
    notifyListeners();
  }

  Future<void> fetchUserPermisos() async {
    _isLoading = true;
    notifyListeners();

    try {
      int? userId = await SessionStorage().getId();
      if (userId != null) {
        var db = await RepoService().db;

        var query = await db!.query(
          'UsuarioPermiso',
          where: 'idUsuario = ?',
          whereArgs: [userId],
        );

        _userPermisos =
            query.map((row) => row['idPermiso'].toString()).toList();
      }
    } catch (e) {
      print('Error fetching user permisos: $e');
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }
}
