import 'package:flutter/material.dart';
// import 'package:http/http.dart' as http;  // /* 사용안함. Api.serverRequest() 사용 */
import 'dart:convert' show utf8, jsonEncode;
import 'package:crypto/crypto.dart';
import 'package:shared_preferences/shared_preferences.dart';

// 회원가입 모달창
import '../../dialogs/signup_dialog.dart';

/* 우리의 Api 모듈 */
import '../../plugins/api.dart';

/* 안내 모달창 */
import '../../dialogs/response_dialog.dart';

/* (기존) ID/PW 찾기, 회원가입 페이지 */
import 'id_finding_page.dart';  /* ID 찾기 페이지 임포트 */
import 'pw_finding_page.dart';  /* PW 찾기 페이지 임포트 */
import 'signup_page.dart';      /* 회원가입 페이지 임포트 */

/* 구글 로그인 */
import 'package:google_sign_in/google_sign_in.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'dart:io' show Platform;

/* 애플 로그인 */
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

/* 광고 */
import 'package:google_mobile_ads/google_mobile_ads.dart';

/* 메인 페이지 */
import '../room/main_page.dart';


/* 설정 */
import '../../config/config.dart';

/* 뒤로가기 */
import 'package:fluttertoast/fluttertoast.dart'; // /* 뒤로가기 안내 문구에 Toast 등 사용 */

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

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  // ─────────────────────────────────────────
  // (A) ID/PW 관련 (아이디/비밀번호)
  // ─────────────────────────────────────────
  final TextEditingController idController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();
  bool autoLogin = false; // /* 자동로그인 체크박스 */
  String loginErrorMessage = ''; // /* 로그인 실패 시 안내 */

  // ─────────────────────────────────────────
  // (B) 구글 로그인 객체
  // ─────────────────────────────────────────
  final GoogleSignIn _googleSignIn = GoogleSignIn(scopes: <String>['email']);

  // ─────────────────────────────────────────
  // (C) 광고 배너
  // ─────────────────────────────────────────
  BannerAd? _bannerAd;
  bool _isBannerReady = false;
  String adUnitId = Config.adUnitId; // /* 실제/테스트 배너 광고 단위 ID */

  // 뒤로가기 처리 (2초 이내 두 번 누르면 종료)
  DateTime? _lastPressedTime;
  static const _exitDuration = Duration(seconds: 2);

  // 로딩 중 표시
  bool _isLoading = false;

  Future<bool> _onWillPop() async {
    final now = DateTime.now();
    if (_lastPressedTime == null || now.difference(_lastPressedTime!) > _exitDuration) {
      _lastPressedTime = now;
      /* 안내 문구 띄우기 (Toast) */
      Fluttertoast.showToast(
        msg: 'Press again to exit the app.' 
        /* '한 번 더 누르면 앱이 종료됩니다.' */,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
      );
      return false;
    }
    // 2초 내 두 번 누르면 앱 종료
    return true;
  }

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

  void _initBannerAd() {
    _bannerAd = BannerAd(
      adUnitId: adUnitId,
      size: AdSize.banner,
      request: const AdRequest(),
      listener: BannerAdListener(
        onAdLoaded: (ad) {
          setState(() => _isBannerReady = true);
        },
        onAdFailedToLoad: (ad, error) {
          ad.dispose();
        },
      ),
    );
    _bannerAd?.load();
  }

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

  // ─────────────────────────────────────────
  // (D1) ID/PW 로그인
  // ─────────────────────────────────────────
  Future<void> _loginWithIdPw() async {
    setState(() => _isLoading = true);
    final id = idController.text.trim();
    final pw = passwordController.text.trim();

    // 비밀번호 SHA-256 해싱
    final bytes = utf8.encode(pw);
    final digest = sha256.convert(bytes);
    final hashedPw = digest.toString();

    final requestBody = {
      "user_id": id,
      "user_pw": hashedPw,
    };

    try {
      // (1) /user/login 서버 요청
      final response = await Api.serverRequest(uri: '/user/login', body: requestBody);

      if (response['result'] == 'OK') {
        /* 내부 응답 */
        final resp = response['response'] ?? {};
        if (resp['result'] == 'OK') {
          /* 로그인 성공 */
          final prefs = await SharedPreferences.getInstance();
          await prefs.setString('oauth_type', 'idpw');
          await prefs.setBool('auto_login', true);
          await prefs.setString('jwt_token', resp['auth']['token'].toString());
          await prefs.setInt('my_user_seq', resp['auth']['user_seq']);

          if (!mounted) return;
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (_) => const MainPage()),
          );
        } else {
          // 로그인 실패
          showResponseDialog(context, resp['response_info']['msg_title'], resp['response_info']['msg_content']);
        }
      } else {
        // 서버 통신 FAIL
        showResponseDialog(context, 'Error' /* 오류 */, 'Login request failed.' 
            /* 로그인 요청 실패 */);
      }
    } catch (e) {
      showResponseDialog(context, 'Error' /* 오류 */, 'Exception occurred during login request.\n$e' 
          /* 로그인 요청 중 예외 발생.\n$e */);
    } finally {
      setState(() => _isLoading = false);
    }
  }

  // ─────────────────────────────────────────
  // (D2) 구글 로그인
  // ─────────────────────────────────────────
  Future<void> _googleLogin() async {
    setState(() => _isLoading = true);
    try {
      // 1) 구글 계정 선택
      final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
      if (googleUser == null) {
        // 취소
        return;
      }

      // 2) 구글 인증 정보
      final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
      // 3) FirebaseAuth Credential
      final AuthCredential credential = GoogleAuthProvider.credential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );

      // 4) FirebaseAuth로 로그인
      final UserCredential userCredential = await FirebaseAuth.instance.signInWithCredential(credential);
      final User? user = userCredential.user;
      if (user == null) {
        showResponseDialog(context, 'Error' /* 오류 */, 'Google login error. Please contact the administrator.' 
            /* 구글 로그인 오류. 관리자에게 문의해주세요. */);
        return;
      }

      final idToken = await user.getIdToken();
      // 서버에 구글 로그인 정보 전송
      final requestBody = {
        'id_token': idToken,
      };

      final response = await Api.serverRequest(uri: '/user/google/login', body: requestBody);
      if (response['result'] == 'OK') {
        final resp = response['response'] ?? {};
        if (resp['result'] == 'OK') {
          final prefs = await SharedPreferences.getInstance();
          await prefs.setString('oauth_type', 'google');
          await prefs.setBool('auto_login', true);
          await prefs.setString('jwt_token', resp['auth']['token'].toString());
          await prefs.setInt('my_user_seq', resp['auth']['user_seq']);

          Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => const MainPage()));
        } else {
          showResponseDialog(context, resp['response_info']['msg_title'], resp['response_info']['msg_content']);
        }
      } else {
        showResponseDialog(context, 'Error' /* 오류 */, 'Google login request failed.'
            /* 구글 로그인 요청 실패 */);
      }
    } catch (e) {
      _showAlert('Error' /* 오류 */, 'An error occurred during Google login.\n$e' 
          /* 구글 로그인 중 오류가 발생했습니다.\n$e */);
    } finally {
      setState(() => _isLoading = false);
    }
  }


  // ─────────────────────────────────────────
  // (D4) 애플 로그인
  // ─────────────────────────────────────────
  Future<void> _appleLogin() async {
    setState(() => _isLoading = true);
    try {
      // 1) 애플 로그인 시도
      final appleCredential = await SignInWithApple.getAppleIDCredential(
        scopes: [
          AppleIDAuthorizationScopes.email,
          AppleIDAuthorizationScopes.fullName,
        ],
      );

      // 2) Firebase 용 credential 생성
      final oauthCredential = OAuthProvider('apple.com').credential(
        idToken: appleCredential.identityToken,
        accessToken: appleCredential.authorizationCode,
      );

      // 3) Firebase Auth로 로그인
      final UserCredential userCredential = 
          await FirebaseAuth.instance.signInWithCredential(oauthCredential);
      final User? user = userCredential.user;
      
      if (user == null) {
        showResponseDialog(context, 'Error' /* 오류 */, 
            'Apple login error. Please contact the administrator.' 
            /* 애플 로그인 오류. 관리자에게 문의해주세요. */);
        return;
      }

      // 4) Firebase 토큰 가져오기
      final idToken = await user.getIdToken();
      
      // 5) 서버에 애플 로그인 정보 전송
      final requestBody = {
        'id_token': idToken,
      };

      final response = await Api.serverRequest(uri: '/user/apple/login', body: requestBody);
      
      if (response['result'] == 'OK') {
        final resp = response['response'] ?? {};
        if (resp['result'] == 'OK') {
          // 로그인 성공 시 정보 저장
          final prefs = await SharedPreferences.getInstance();
          await prefs.setString('oauth_type', 'apple');
          await prefs.setBool('auto_login', true);
          await prefs.setString('jwt_token', resp['auth']['token'].toString());
          await prefs.setInt('my_user_seq', resp['auth']['user_seq']);

          // 메인 페이지로 이동
          Navigator.pushReplacement(context, 
              MaterialPageRoute(builder: (_) => const MainPage()));
        } else {
          showResponseDialog(context, 
              resp['response_info']['msg_title'], 
              resp['response_info']['msg_content']);
        }
      } else {
        showResponseDialog(context, 'Error' /* 오류 */, 
            'Apple login request failed.' /* 애플 로그인 요청 실패 */);
      }
    } catch (e) {
      _showAlert('Error' /* 오류 */, 
          'An error occurred during Apple login.\n$e'
          /* 애플 로그인 중 오류가 발생했습니다.\n$e */);
    } finally {
      setState(() => _isLoading = false);
    }
  }
  

  // ─────────────────────────────────────────
  // (F) 간단 Alert (간단 알림창)
  // ─────────────────────────────────────────
  void _showAlert(String title, String message) {
    showDialog(
      context: context,
      builder: (_) => AlertDialog(
        backgroundColor: Colors.white,
        title: Text(title, style: const TextStyle(color: Colors.black)),
        content: Text(message, style: const TextStyle(color: Colors.black)),
        actions: [
          TextButton(
            style: TextButton.styleFrom(
              backgroundColor: Colors.black,
              foregroundColor: Colors.white,
            ),
            onPressed: () => Navigator.pop(context),
            child: const Text('OK' /* 확인 */),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Stack(
        children: [
          Scaffold(
            backgroundColor: Colors.white,
            appBar: AppBar(
              title: const Text(
                'ALL SCORE'
                /* ALL SCORE */,
                style: TextStyle(color: Colors.white),
              ),
              backgroundColor: Colors.black,
            ),
            body: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                // (1) 중앙 영역 → 로그인 UI
                Expanded(
                  child: Center(
                    child: SingleChildScrollView(
                      padding: const EdgeInsets.all(16),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          // ─────────────────────────────────────────
                          // 1. 올스코어 로그인 (ID/PW)
                          // ─────────────────────────────────────────
                          const Text(
                            'ALLSCORE Login'
                            /* 올스코어 로그인 */,
                            style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: Colors.black),
                          ),
                          const SizedBox(height: 16),

                          // (A) 아이디 입력
                          SizedBox(
                            width: 300,
                            child: TextField(
                              controller: idController,
                              decoration: InputDecoration(
                                labelText: 'ID' 
                                /* 아이디 */,
                                border: OutlineInputBorder(
                                  borderSide: const BorderSide(color: Colors.black),
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                enabledBorder: OutlineInputBorder(
                                  borderSide: const BorderSide(color: Colors.black),
                                  borderRadius: BorderRadius.circular(8),
                                ),
                              ),
                            ),
                          ),
                          const SizedBox(height: 12),

                          // (B) 비밀번호 입력
                          SizedBox(
                            width: 300,
                            child: TextField(
                              controller: passwordController,
                              obscureText: true,
                              decoration: InputDecoration(
                                labelText: 'PW' 
                                /* 비밀번호 */,
                                border: OutlineInputBorder(
                                  borderSide: const BorderSide(color: Colors.black),
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                enabledBorder: OutlineInputBorder(
                                  borderSide: const BorderSide(color: Colors.black),
                                  borderRadius: BorderRadius.circular(8),
                                ),
                              ),
                            ),
                          ),

                          // (C) 로그인 에러
                          if (loginErrorMessage.isNotEmpty)
                            Padding(
                              padding: const EdgeInsets.only(top: 8.0),
                              child: Text(
                                loginErrorMessage,
                                style: const TextStyle(color: Colors.red),
                              ),
                            ),

                          const SizedBox(height: 8),

                          // (D) 자동로그인 체크박스
                          SizedBox(
                            width: 300,
                            child: Row(
                              children: [
                                Checkbox(
                                  value: autoLogin,
                                  onChanged: (val) {
                                    setState(() {
                                      autoLogin = val ?? false;
                                    });
                                  },
                                ),
                                const Text(
                                  'Auto Login' 
                                  /* 자동로그인 */,
                                  style: TextStyle(color: Colors.black),
                                ),
                              ],
                            ),
                          ),

                          // (E) 로그인 버튼
                          SizedBox(
                            width: 300,
                            child: ElevatedButton(
                              style: ElevatedButton.styleFrom(
                                backgroundColor: Colors.white,
                                foregroundColor: Colors.black,
                                side: const BorderSide(color: Colors.black),
                                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                              ),
                              onPressed: _loginWithIdPw,
                              child: const Text(
                                'Login' 
                                /* 로그인 */,
                              ),
                            ),
                          ),

                          // (F) ID/PW 찾기, 회원가입
                          const SizedBox(height: 8),
                          TextButton(
                            onPressed: () {
                              Navigator.push(context, MaterialPageRoute(builder: (_) => const IdFindingPage()));
                            },
                            child: const Text(
                              'Find ID' 
                              /* ID 찾기 */,
                              style: TextStyle(color: Colors.black),
                            ),
                          ),
                          TextButton(
                            onPressed: () {
                              Navigator.push(context, MaterialPageRoute(builder: (_) => const PwFindingPage()));
                            },
                            child: const Text(
                              'Find PW' 
                              /* PW 찾기 */,
                              style: TextStyle(color: Colors.black),
                            ),
                          ),
                          TextButton(
                            onPressed: () {
                              // Navigator.push(context, MaterialPageRoute(builder: (_) => const SignUpPage()));
                              showDialog(
                                context: context,
                                builder: (_) => const SignUpDialog(),
                              );
                            },
                            child: const Text(
                              'Sign Up' 
                              /* 회원가입 */,
                              style: TextStyle(color: Colors.black),
                            ),

                          ),

                          const SizedBox(height: 24),
                          const Divider(height: 1, color: Colors.black),
                          const SizedBox(height: 24),

                          // ─────────────────────────────────────────
                          // 2. 구글 로그인 / 회원가입
                          // ─────────────────────────────────────────
                          const Text(
                            'Social Login'
                            /* 구글 계정 */,
                            style: TextStyle(fontSize: 20, color: Colors.black, fontWeight: FontWeight.bold),
                          ),
                          const SizedBox(height: 16),

                          // (a) 구글 로그인
                          // 소셜 로그인 버튼들을 Row로 배치
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              // 구글 로그인 버튼
                              Container(
                                width: 140,
                                margin: const EdgeInsets.symmetric(horizontal: 5),
                                child: ElevatedButton.icon(
                                  icon: Container(
                                    width: 24,
                                    height: 24,
                                    decoration: const BoxDecoration(
                                      image: DecorationImage(
                                        image: AssetImage('assets/images/icons8-google-logo-48.png'),
                                        fit: BoxFit.contain,
                                      ),
                                    ),
                                  ),
                                  label: const Text(
                                    'Google',
                                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                                  ),
                                  style: ElevatedButton.styleFrom(
                                    backgroundColor: Colors.white,
                                    foregroundColor: Colors.black,
                                    side: const BorderSide(color: Colors.black),
                                    padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
                                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                                  ),
                                  onPressed: _googleLogin,
                                ),
                              ),

                              // 애플 로그인 버튼 - 아이폰에서만 활성화
                              if (Platform.isIOS)
                                Container(
                                  width: 140,
                                  margin: const EdgeInsets.symmetric(horizontal: 5),
                                  child: ElevatedButton.icon(

                                    icon: const Icon(
                                      Icons.apple,
                                      size: 24,
                                      color: Colors.black,
                                    ),
                                    label: const Text(
                                      'Apple',
                                      style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                                    ),
                                    style: ElevatedButton.styleFrom(
                                      backgroundColor: Colors.white,
                                      foregroundColor: Colors.black,
                                      side: const BorderSide(color: Colors.black),
                                      padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
                                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                                    ),
                                    onPressed: _appleLogin,
                                  ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ),

                // (2) 하단 광고 영역
                if (_isBannerReady && _bannerAd != null)
                  Container(
                    width: _bannerAd!.size.width.toDouble(),
                    height: _bannerAd!.size.height.toDouble(),
                    alignment: Alignment.center,
                    child: AdWidget(ad: _bannerAd!),
                  ),
              ],
            ),
          ),

          // 로딩 중일 때 오버레이
          if (_isLoading)
            Container(
              width: double.infinity,
              height: double.infinity,
              color: Colors.black54,
              alignment: Alignment.center,
              child: const CircularProgressIndicator(color: Colors.white),
            ),
        ],
      ),
    );
  }
}
