import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:shared_preferences/shared_preferences.dart';
// Other imports...

import '../../dialogs/settings_dialog.dart';
import 'create_room_page.dart';
import 'room_search_home_page.dart';

// Ongoing games (진행중 방)
import 'playing_private_page.dart';
import 'playing_team_page.dart';

// Temporary: server API & dialogs (임시: 서버 API & 모달)
import '../../plugins/api.dart';
import '../../dialogs/response_dialog.dart';

// For back-button handling (뒤로가기)
import 'package:fluttertoast/fluttertoast.dart'; // Toast for back-button notice

// Config (설정)
import '../../config/config.dart';

// Survey (설문조사)
import '../../dialogs/survey_dialog.dart';

// Ads (광고)
import '../../plugins/admob.dart';

class MainPage extends StatefulWidget {
  const MainPage({Key? key}) : super(key: key);

  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  // Handle back button (뒤로가기 처리)
  DateTime? _lastPressedTime;

  // e.g., if a second back press occurs within 2 seconds, exit the app (2초 이내로 두 번 누르면 종료)
  static const _exitDuration = Duration(seconds: 2);

  double scaleFactor = 1.0;

  @override
  void initState() {
    super.initState();

    // (A) When entering the main page, disconnect from Firebase Realtime Database 
    //     (메인 페이지 들어올 때 전체 FRD 연결 해제)
    FirebaseDatabase.instance.goOffline();

    // (B) Check landing page info (랜딩 페이지 정보 확인)
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _checkLandingMainPageInfo();
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _updateScaleFactor();
  }

  // Adjust font size by screen width (화면 크기에 따라 폰트 크기 조절)
  void _updateScaleFactor() {
    final screenWidth = MediaQuery.of(context).size.width;
    const baseWidth = 400.0;
    setState(() {
      scaleFactor = (screenWidth / baseWidth).clamp(0.8, 1.4);
    });
  }

  // On back press callback (뒤로가기 콜백)
  Future<bool> _onWillPop() async {
    final now = DateTime.now();
    if (_lastPressedTime == null ||
        now.difference(_lastPressedTime!) > _exitDuration) {
      // First back press or last press was long ago
      // (첫 번째 뒤로가기 누름 혹은 이전 누름이 오래 전)
      _lastPressedTime = now;

      // Show toast message (안내 문구 띄우기)
      Fluttertoast.showToast(
        msg: 'Press again to exit the app.', // '한 번 더 누르면 앱이 종료됩니다.'
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
      );
      return false; // Do not pop the page
    }
    // If second press within 2 seconds → exit the app (2초 이내 두 번째 누름 → 종료)
    return true; 
  }

  /// (B) Check "force exit" from server → if there's a room, re-enter 
  ///     (서버에 "강제 종료 여부" 확인 → 방이 있으면 재입장)
  Future<void> _checkLandingMainPageInfo() async {
    try {
      final Map<String, dynamic> requestBody = {};
      final response = await Api.serverRequest(
        uri: '/room/score/landing/mainpage/info',
        body: requestBody,
      );

      if (response['result'] == 'OK') {
        final resp = response['response'] ?? {};
        if (resp['result'] == 'OK') {
          final data = resp['data'] ?? {};
          final forceExitYn = (data['force_exit_yn'] ?? 'N').toString().toUpperCase();

          if (forceExitYn == 'Y') {
            final int roomSeq = data['room_seq'] ?? 0;
            final String roomType = (data['room_type_name'] ?? '').toString().toUpperCase();
            final String roomTitle = (data['room_title'] ?? '').toString();

            // (1) Restore FRD connection before re-entering (재입장 전 FRD 연결 복원)
            FirebaseDatabase.instance.goOnline();

            showResponseDialog(
              context, 
              'Re-enter Game',  // '게임 재입장'
              'You will re-enter the forcibly closed game.'  // '강제 종료 된 게임에 재입장 합니다.'
            );

            // (2) Navigate based on the room type (방 타입에 따라 이동)
            if (roomType == 'TEAM') {
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(
                  builder: (_) => PlayingTeamPage(
                    roomSeq: roomSeq,
                    roomTitle: roomTitle.isNotEmpty 
                        ? roomTitle 
                        : 'Re-enter (Team)', // '재입장 (팀전)'
                  ),
                ),
              );
            } else {
              // Private
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(
                  builder: (_) => PlayingPrivatePage(
                    roomSeq: roomSeq,
                    roomTitle: roomTitle.isNotEmpty 
                        ? roomTitle 
                        : 'Re-enter (Private)', // '재입장 (개인전)'
                  ),
                ),
              );
            }
          }
          final surveyYn = (data['survey_yn'] ?? 'N').toString().toUpperCase();
          final joinGameYn = (data['join_game_yn'] ?? 'N').toString().toUpperCase();
          final prefs = await SharedPreferences.getInstance();
          final surveyShownToday = prefs.getString('survey_popup_today') ?? 'N';
          final nickname = (data['nickname'] ?? '').toString();

          // If user hasn't taken the survey, they have joined a game before, 
          // and haven't shown survey today → show popup
          if (surveyYn == 'N' && joinGameYn == 'Y' && surveyShownToday == 'N') {
            Future.delayed(Duration.zero, () {
              showSurveyDialog(context, nickname); 
              // '설문조사 팝업 표시'
            });
          }
        } else {
          final msgTitle = resp['response_info']?['msg_title'] ?? 'Error';  // '오류'
          final msgContent = resp['response_info']?['msg_content'] ?? 'Failed to check forced exit'; 
          // '강제 종료 여부 확인 실패'
          showResponseDialog(context, msgTitle, msgContent);
        }
      } else {
        showResponseDialog(
          context, 
          'Server Error', // '서버 오류'
          'Failed to check forced exit.' // '강제 종료 여부 확인에 실패했습니다.'
        );
      }
    } catch (e) {
      showResponseDialog(
        context, 
        'Server Error', // '서버 오류'
        'Failed to check forced exit.' // '강제 종료 여부 확인에 실패했습니다.'
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.black,
          elevation: 0,
          automaticallyImplyLeading: false, // Do not show back button (뒤로가기 버튼 X)
          title: const Text(
            'ALLSCORE',
            style: TextStyle(color: Colors.white),
          ),
          actions: [
            IconButton(
              icon: const Icon(Icons.settings, color: Colors.white),
              onPressed: () {
                // Open settings dialog (설정 모달 열기)
                showSettingsDialog(context);
              },
            ),
          ],
        ),

        bottomNavigationBar: AdBannerWidget(),

        body: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            // Middle buttons (중앙 버튼)
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Center(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      _buildBlackWhiteButton(
                        label: 'Create\nRoom', // '방만들기'
                        onTap: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(builder: (_) => const CreateRoomPage()),
                          );
                        },
                      ),
                      const SizedBox(width: 16),
                      _buildBlackWhiteButton(
                        label: 'Join', // '참여하기'
                        onTap: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(builder: (_) => const RoomSearchHomePage()),
                          );
                        },
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBlackWhiteButton({
    required String label,
    required VoidCallback onTap,
  }) {
    return SizedBox(
      width: 100 * scaleFactor,
      height: 100 * scaleFactor,
      child: ElevatedButton(
        onPressed: onTap,
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.white,
          foregroundColor: Colors.black,
          side: const BorderSide(color: Colors.black, width: 1),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        ),
        child: Text(
          label, 
          style: TextStyle(color: Colors.black, fontSize: 12 * scaleFactor),
          textAlign: TextAlign.center,
        ),
      ),
    );
  }
}
