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

class VariableViewModel extends ChangeNotifier {
  String _busqueda = "";
  String get busqueda => _busqueda;

  List<Variable> _variables = [];
  bool _isLoading = false;
  Variable? _selectedVariable;

  List<Variable> get variables => _variables;
  Variable? get selectedVariable => _selectedVariable;
  bool get isLoading => _isLoading;

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

  int get currentPage => _currentPage;
  int get totalVariables => _totalVariables;
  int get totalPages => (_totalVariables / _limit).ceil();

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

  void selectVariable(Variable variable) {
    _selectedVariable = variable;
    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 Variable'));
    _totalVariables = count ?? 0;

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

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

  Future<void> fetchLocalByName({required String nombre}) async {
    var db = await RepoService().db;
    var query = await db!.query(
      'Variable',
      where: 'nombre LIKE "%$nombre%"',
      orderBy: 'id asc',
    );
    List<Variable> aux = [];
    for (var element in query) {
      Variable variable = Variable.fromJson(element);
      aux.add(variable);
    }
    _variables = aux;
    notifyListeners();
  }

  Future<void> addVariable(Variable variable) async {
    await RepoService().guardar(variable);
    fetchLocalAll();
  }

  Future<void> updateVariable(Variable variable) async {
    setIsLoading(true);
    try {
      await RepoService().guardar(variable);
      fetchLocalAll();
    } catch (e) {
      print('Error updating variable: $e');
    }
    setIsLoading(false);
  }

  Future<void> deleteVariable(int id) async {
    await RepoService().eliminar<Variable>(id);
    fetchLocalAll();
  }

  void setIsLoading(bool loading) {
    _isLoading = loading;
    notifyListeners();
  }

  void nextPage() {
    if (_currentPage < totalPages) {
      fetchLocalAll(page: _currentPage + 1);
    }
  }

  void previousPage() {
    if (_currentPage > 1) {
      fetchLocalAll(page: _currentPage - 1);
    }
  }

  Future<bool> isVariableActive(String clave) async {
    var db = await RepoService().db;
    var result = await db!.query(
      'Variable',
      where: 'clave = ?',
      whereArgs: [clave],
    );

    if (result.isNotEmpty) {
      var variable = Variable.fromJson(result.first);
      return variable.activo == true;
    }

    return false;
  }

  Future<Variable?> getVariableByClave(String nombre) async {
    var db = await RepoService().db;
    var result = await db!.query(
      'Variable',
      where: 'nombre = ?',
      whereArgs: [nombre],
    );

    if (result.isNotEmpty) {
      return Variable.fromJson(result.first);
    }

    return null;
  }
}
