import 'package:flutter/material.dart';
import '../game/model/item.dart';
import '../game/model/entity.dart';
import '../game/data/item_table.dart';
import '../game/enums.dart';
import '../game/config/game_config.dart';
import '../utils/game_math.dart';

class ShopProvider with ChangeNotifier {
  List<Item> availableItems = [];
  String _lastShopMessage = '';

  String get lastShopMessage => _lastShopMessage;

  void clearMessage() {
    _lastShopMessage = '';
    notifyListeners();
  }

  void generateShopItems(int stage) {
    ItemTier currentTier = ItemTier.tier1;
    if (stage > GameConfig.tier2StageMax)
      currentTier = ItemTier.tier3;
    else if (stage > GameConfig.tier1StageMax)
      currentTier = ItemTier.tier2;

    availableItems = [];
    for (int i = 0; i < 4; i++) { // Generate 4 items
      ItemTemplate? template = ItemTable.getRandomItem(tier: currentTier);
      if (template != null) {
        availableItems.add(template.createItem(stage: stage));
      }
    }
    notifyListeners();
  }

  bool rerollShopItems(Character player, int currentStageNumber) {
    const int rerollCost = GameConfig.shopRerollCost;
    if (player.gold >= rerollCost) {
      player.gold -= rerollCost;
      generateShopItems(currentStageNumber); // Regenerate based on current stage
      _lastShopMessage = "Shop items rerolled for $rerollCost G.";
      notifyListeners();
      return true;
    } else {
      _lastShopMessage = "Not enough gold to reroll!";
      notifyListeners();
      return false;
    }
  }

  bool buyItem(Item item, Character player) {
    if (player.gold >= item.price) {
      if (player.inventory.length < player.maxInventorySize) {
        player.gold -= item.price;
        player.addToInventory(item);
        availableItems.remove(item); // Remove from shop
        _lastShopMessage = "Bought ${item.name} for ${item.price} G.";
        notifyListeners();
        return true;
      } else {
        _lastShopMessage = "Inventory is full! Cannot buy ${item.name}.";
        notifyListeners();
        return false;
      }
    } else {
      _lastShopMessage = "Not enough gold!";
      notifyListeners();
      return false;
    }
  }
}
