//import 'dart:ffi';
//import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:gifunavi/model/destination.dart';
import 'package:gifunavi/pages/destination/destination_controller.dart';
import 'package:gifunavi/pages/index/index_controller.dart';
import 'package:gifunavi/services/DatabaseService.dart';
//import 'package:gifunavi/utils/database_helper.dart';
import 'package:gifunavi/widgets/GameState/CheckinState.dart';
import 'package:gifunavi/widgets/GameState/ConnectionStatus.dart';
//import 'package:gifunavi/widgets/GameState/DashboardWidget.dart';
import 'package:gifunavi/widgets/GameState/game_on_off.dart';
//import 'package:gifunavi/widgets/GameState/Colors.dart';
import 'package:gifunavi/widgets/gps_status.dart';
import 'package:gifunavi/utils/location_controller.dart';

class GameStateManager {
  static final GameStateManager _instance = GameStateManager._internal();

  factory GameStateManager() {
    return _instance;
  }

  GameStateManager._internal();

  final List<String> _logs = [];
  final List<VoidCallback> _listeners = [];

  List<String> get logs => _logs;

  void addLog(String log) {
    _logs.add(log);
    _notifyListeners(); // Notify all listeners
  }

  void clearLogs() {
    _logs.clear();
    _notifyListeners(); // Notify all listeners
  }

  void addListener(VoidCallback listener) {
    _listeners.add(listener);
  }

  void removeListener(VoidCallback listener) {
    _listeners.remove(listener);
  }

  void _notifyListeners() {
    for (var listener in _listeners) {
      listener();
    }
  }
}

class GameStateWidget extends StatefulWidget {
  const GameStateWidget({super.key});

  @override
  State<GameStateWidget> createState() => _GameStateWidgetState();
}

class _GameStateWidgetState extends State<GameStateWidget> {
  final GameStateManager gameStateManager = GameStateManager();

  final IndexController indexController = Get.find<IndexController>();
  final DestinationController destinationController =
      Get.find<DestinationController>();

  @override
  void initState() {
    super.initState();
    gameStateManager.addListener(_updateLogs);
  }

  @override
  void dispose() {
    gameStateManager.removeListener(_updateLogs);
    super.dispose();
  }

  void _updateLogs() {
    Future.delayed(Duration.zero, () {
      if (mounted) {
        setState(() {});
      }
    });
  }

  void toggleExpanded() {
    setState(() {
      isExpanded = !isExpanded;
    });
  }

  void clearLogs() {
    gameStateManager.clearLogs();
  }

  bool isExpanded = false;

  @override
  Widget build(BuildContext context) {
    final DatabaseService dbService = DatabaseService();
    //final LocationController locationController = Get.find<LocationController>();
    return Container(
      width: MediaQuery.of(context).size.width,
      decoration: const BoxDecoration(color: Colors.black12),
      child: GestureDetector(
        onTap: toggleExpanded,
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 200),
          color: isExpanded ? Colors.black54 : Colors.black12,
          height: isExpanded ? 160.0 : 48.0, // Adjust sizes as needed
          child: Column(
            children: [
              // Top bar with clear button
              if (isExpanded)
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 10.0),
                  color: Colors.blueGrey, // Adjust color as needed
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Text('game_status'.tr, style: const TextStyle(color: Colors.white)),
                      IconButton(
                        icon: const Icon(Icons.clear, color: Colors.white),
                        onPressed: toggleExpanded,
                      ),
                    ],
                  ),
                ),

              // Log messages
              Expanded(
                child: SingleChildScrollView(
                  child: Wrap(
                    alignment: WrapAlignment.spaceEvenly,
                    children: [
                      Obx(() => Padding(
                            padding: const EdgeInsets.all(4.0),
                            child: GameStatusIndicator(
                              gameStarted: destinationController.isInRog.value,
                              minimized: !isExpanded,
                            ),
                          )),
                      Padding(
                        padding: const EdgeInsets.all(4.0),
                        child: StreamBuilder<List<Destination>>(
                          stream: dbService.destinationUpdatesStream,
                          initialData: const [], // 初期値を設定
                          builder: (context, snapshot) {
                            if (snapshot.hasError) {
                              print('Error: ${snapshot.error}');
                              return LocationVisitedWidget(
                                count: 0,
                                minimized: !isExpanded,
                              );
                            }
                            // データがある場合はそのデータを使用し、ない場合は空のリストを使用
                            final destinations = snapshot.data ?? [];

                            return LocationVisitedWidget(
                              count: destinations.length,
                              minimized: !isExpanded,
                            );

                          },
                        ),

                        // child: LocationVisitedWidget(
                        //   count:
                        //   minimized: !isExpanded,
                        // ),
                      ),
                      Padding(
                        padding: const EdgeInsets.all(4.0),
                        child: Obx(() => ConnectionStatusIndicator(
                            connectionStatus: (indexController
                                            .connectionStatusName.value.toLowerCase() ==
                                        "wifi" ||
                                    indexController
                                            .connectionStatusName.value.toLowerCase() ==
                                        "mobile")
                                ? indexController.connectionStatusName.value.toLowerCase() ==
                                        "wifi"
                                    ? ConnectionStatus.wifi
                                    : ConnectionStatus.mobile
                                : ConnectionStatus.none,
                            minimized: !isExpanded)),
                      ), // Expanded view
                      Padding(
                          padding: const EdgeInsets.all(4.0),
                          child:GpsSignalStrengthIndicator(
                            locationController: Get.find<LocationController>(),
                            minimized: !isExpanded, // isExpanded はあなたのロジックに依存した変数),
                          )
                      ),
                    ],
                  ),
                  // child: Obx(
                  //   () => DashboardWidget(
                  //     gameStarted: destinationController.isInRog.value,
                  //     locationsVisited: 3,
                  //     isMinimized: false,
                  //   ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
