import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import '../../../base/base_screen.dart';
import '../../../base/basic_state.dart';
import '../../../main.dart';
import '../../../widgets/back_button.dart';
import '../models/game_bundle_item_model.dart';
import '../models/game_card_item_model.dart';
import 'game_card_viewmodel.dart';

class GameCardScreen extends BaseScreen {
  const GameCardScreen({super.key});

  @override
  State<GameCardScreen> createState() => _GameCardScreenState();
}

class _GameCardScreenState extends BaseState<GameCardScreen> with BasicState, RouteAware {
  final GameCardViewModel _viewModel = Get.put(GameCardViewModel());

  @override
  void initState() {
    super.initState();
    String gameId = '';
    GameBundleItemModel? data;
    final args = Get.arguments;
    if (args is Map) {
      data = args['data'] as GameBundleItemModel?;
      gameId = args['gameId'] as String? ?? '';
    }
    if (data == null && gameId.isEmpty) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        Get.back();
      });
      return;
    }
    if (data != null) {
      _viewModel.data.value = data;
    }
    if (gameId.isNotEmpty) {
      _viewModel.getGameDetail(id: gameId);
    }
    _viewModel.onShowAlertError = (message, onClose) {
      if (message.isEmpty) return;
      showAlertError(content: message, showCloseButton: !onClose, onConfirmed: () {
        if (!onClose) return;
        Get.back();
      });
    };
    _viewModel.submitGameCardSuccess = (popup) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        showPopup(data: popup);
      });
    };
    _viewModel.getGameDetailSuccess = () {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        final popup = _viewModel.data?.value?.popup;
        if (popup == null) return;
        showPopup(data: popup);
      });
    };
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final route = ModalRoute.of(context);
    if (route is PageRoute) {
      routeObserver.subscribe(this, route);
    }
  }

  @override
  void dispose() {
    routeObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  void didPopNext() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Future.delayed(const Duration(milliseconds: 16), () {
        _viewModel.getGameDetail();
      });
    });
  }

  @override
  Widget createBody() {
    return Scaffold(
      body: Obx(() {
        final data = _viewModel.data.value;
        if (data == null) {
          return const SizedBox();
        }
        final cards = data?.options ?? [];
        final screenHeight = MediaQuery.of(context).size.height;
        final startTop = screenHeight * 560 / 1920;

        return Stack(
          children: [
            Container(
              decoration: BoxDecoration(
                image:
                data?.background != null
                    ? DecorationImage(image: NetworkImage(data?.background ?? ''), fit: BoxFit.cover)
                    : null,
                color: Colors.green[100],
              ),
            ),
            // Button Back
            SafeArea(child: Padding(padding: const EdgeInsets.all(8), child: CustomBackButton())),
            Positioned(
              top: startTop,
              left: 16,
              right: 16,
              bottom: 0,
              child: GridView.builder(
                physics: const NeverScrollableScrollPhysics(),
                itemCount: cards.length,
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  mainAxisSpacing: 20,
                  crossAxisSpacing: 20,
                  childAspectRatio: 3 / 4,
                ),
                itemBuilder: (context, index) {
                  final card = cards[index];
                  return GameCardItem(card: card, onTapCard: () {
                    _viewModel.submitGameCard(data?.id ?? "", card.id ?? 0);
                  });
                },
              ),
            ),
          ],
        );
      }),
    );
  }
}

class GameCardItem extends StatelessWidget {
  final GameCardItemModel card;
  final VoidCallback? onTapCard;
  const GameCardItem({super.key, required this.card, this.onTapCard});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTapCard,
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(18),
          boxShadow: [BoxShadow(color: Colors.black26, blurRadius: 4, offset: Offset(2, 2))],
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Expanded(
              child:
                  card.image != null
                      ? ClipRRect(
                        borderRadius: BorderRadius.circular(16),
                        child: Image.network(card.image!, fit: BoxFit.cover),
                      )
                      : const SizedBox(),
            ),
            const SizedBox(height: 6),
          ],
        ),
      ),
    );
  }
}
