import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../providers/battle_provider.dart';
import '../../../providers/shop_provider.dart';
import '../../../game/model/item.dart';
import '../../../game/config/theme_config.dart';
import '../../../game/config/game_config.dart';
import '../../../game/model/entity.dart';
import '../../utils.dart'; // Import for ToastUtils
import '../inventory/inventory_grid_widget.dart';
import '../common/item_card_widget.dart';

class ShopUI extends StatelessWidget {
  final BattleProvider battleProvider;

  const ShopUI({super.key, required this.battleProvider});

  @override
  Widget build(BuildContext context) {
    return Consumer<ShopProvider>(
      builder: (context, shopProvider, child) {
        final player = battleProvider.player;
        final shopItems = shopProvider.availableItems;

        return Container(
          color: ThemeConfig.shopBg,
          padding: const EdgeInsets.all(16.0),
          child: Column(
            children: [
              // Header
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Row(
                    children: [
                      Icon(
                        Icons.store,
                        size: 32,
                        color: ThemeConfig.mainIconColor,
                      ),
                      SizedBox(width: 8),
                      Text(
                        "Merchant",
                        style: TextStyle(
                          fontSize: 24,
                          fontWeight: FontWeight.bold,
                          color: ThemeConfig.textColorWhite,
                        ),
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      const Icon(
                        Icons.monetization_on,
                        color: ThemeConfig.statGoldColor,
                      ),
                      const SizedBox(width: 4),
                      Text(
                        "${player.gold} G",
                        style: const TextStyle(
                          color: ThemeConfig.statGoldColor,
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
              const Divider(color: ThemeConfig.textColorGrey),
              const SizedBox(height: 8),

              // Shop Items Grid (Top Half)
              Expanded(
                flex: 5,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      "Shop Items",
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: ThemeConfig.textColorWhite,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Expanded(
                      child: shopItems.isEmpty
                          ? const Center(
                              child: Text(
                                "Sold Out",
                                style: TextStyle(
                                  color: ThemeConfig.textColorGrey,
                                  fontSize: 24,
                                ),
                              ),
                            )
                          : GridView.builder(
                              gridDelegate:
                                  const SliverGridDelegateWithFixedCrossAxisCount(
                                    crossAxisCount: 4,
                                    crossAxisSpacing: 8.0,
                                    mainAxisSpacing: 8.0,
                                    childAspectRatio: 0.8,
                                  ),
                              itemCount: shopItems.length,
                              itemBuilder: (context, index) {
                                final item = shopItems[index];
                                final canBuy = player.gold >= item.price;

                                return InkWell(
                                  onTap: () => _showBuyConfirmation(
                                    context,
                                    item,
                                    shopProvider,
                                    player,
                                    battleProvider, // Pass battleProvider
                                  ),
                                  child: ItemCardWidget(
                                    item: item,
                                    showPrice: true,
                                    canBuy: canBuy,
                                  ),
                                );
                              },
                            ),
                    ),
                  ],
                ),
              ),

              const Divider(color: ThemeConfig.textColorGrey),

              // Player Inventory (Bottom Half)
              const Expanded(
                flex: 5,
                child: InventoryGridWidget(mode: InventoryGridMode.shop),
              ),

              const SizedBox(height: 8),

              // Action Buttons
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  ElevatedButton.icon(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: ThemeConfig.btnRerollBg,
                      padding: const EdgeInsets.symmetric(
                        horizontal: 16,
                        vertical: 12,
                      ),
                    ),
                    onPressed: player.gold >= GameConfig.shopRerollCost
                        ? () {
                            bool success = shopProvider.rerollShopItems(
                              player,
                              battleProvider.stage,
                            );
                            if (!success) {
                              ToastUtils.showTopToast(
                                context,
                                "Not enough gold to reroll!",
                              );
                            }
                          }
                        : null,
                    icon: const Icon(
                      Icons.refresh,
                      color: ThemeConfig.textColorWhite,
                    ),
                    label: Text(
                      "Reroll (${GameConfig.shopRerollCost} G)",
                      style: const TextStyle(color: ThemeConfig.textColorWhite),
                    ),
                  ),
                  ElevatedButton.icon(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: ThemeConfig.btnLeaveBg,
                      padding: const EdgeInsets.symmetric(
                        horizontal: 16,
                        vertical: 12,
                      ),
                    ),
                    onPressed: () => battleProvider.proceedToNextStage(),
                    icon: const Icon(
                      Icons.exit_to_app,
                      color: ThemeConfig.textColorWhite,
                    ),
                    label: const Text(
                      "Leave Shop",
                      style: TextStyle(color: ThemeConfig.textColorWhite),
                    ),
                  ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }

  void _showBuyConfirmation(
    BuildContext context,
    Item item,
    ShopProvider shopProvider,
    Character player,
    BattleProvider battleProvider,
  ) {
    if (player.gold < item.price) {
      ToastUtils.showTopToast(
        context,
        "Not enough gold!",
        color: ThemeConfig.snackBarErrorBg,
      );
      return;
    }

    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text("Buy Item"),
        content: Text("Buy ${item.name} for ${item.price} G?"),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(ctx),
            child: const Text("Cancel"),
          ),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
              backgroundColor: ThemeConfig.statGoldColor,
            ),
            onPressed: () {
              bool success = shopProvider.buyItem(item, player);
              Navigator.pop(ctx);

              if (success) {
                battleProvider.refreshUI(); // Update UI
                ToastUtils.showTopToast(
                  context,
                  "Bought ${item.name}",
                  color: Colors.green,
                );
              } else {
                ToastUtils.showTopToast(
                  context,
                  shopProvider.lastShopMessage,
                  color: ThemeConfig.snackBarErrorBg,
                );
              }
            },
            child: const Text("Buy", style: TextStyle(color: Colors.black)),
          ),
        ],
      ),
    );
  }
}
