import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:glowwheels/constants/api.dart';
import 'package:hive/hive.dart';
import 'package:http/http.dart' as http;
import 'package:provider/provider.dart';
import '../models/shop_model.dart';

class ShopProvider with ChangeNotifier {
  ShopModel? _shop;
  String? _token;

  ShopModel? get shop => _shop;
  String? get token => _token;

  final String _shopBox = 'shopBox';
  final String _tokenBox = 'tokenBox';

  ShopProvider() {
    _loadShopAndTokenFromHive();
  }


  void _loadShopAndTokenFromHive() async {
    final shopBox = await Hive.openBox<ShopModel>(_shopBox);
    _shop = shopBox.get('shop');

    final tokenBox = await Hive.openBox<String>(_tokenBox);
    _token = tokenBox.get('token');

    notifyListeners();
  }
  String? getShopId(BuildContext context) {
    return Provider.of<ShopProvider>(context, listen: false).shop?.user.id;
  }

  Future<bool> login(String email, String password) async {
    final loginUri = Uri.parse(ApiConstants.loginUrl);

    try {
      final response = await http.post(
        loginUri,
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode({'email': email, 'password': password}),
      );

      print('Response code: ${response.statusCode}');
      print('Response body: ${response.body}');

      if (response.statusCode == 200) {
        final data = jsonDecode(response.body);

        final shopModel = ShopModel.fromJson(data);

        final shopBox = await Hive.openBox<ShopModel>(_shopBox);
        final tokenBox = await Hive.openBox<String>(_tokenBox);

        await shopBox.put('shop', shopModel);
        await tokenBox.put('token', shopModel.token);

        _shop = shopModel;
        _token = shopModel.token;

        notifyListeners();
        return true;
      } else {
        print('HTTP Error: ${response.statusCode}');
        return false;
      }
    } catch (e) {
      print('Login Exception: $e');
      return false;
    }
  }


  Future<void> logout() async {
    _shop = null;
    _token = null;
    notifyListeners();

    final shopBox = await Hive.openBox<ShopModel>(_shopBox);
    await shopBox.clear();

    final tokenBox = await Hive.openBox<String>(_tokenBox);
    await tokenBox.clear();
  }

  void setShop(ShopModel shop) {
    _shop = shop;
    notifyListeners();
  }

  void setToken(String token) {
    _token = token;
    notifyListeners();
  }
}
