import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:convert' show utf8;
import 'login_page.dart';
import 'pw_finding_page.dart';
import 'signup_page.dart';
import '../../dialogs/response_dialog.dart';
import '../../plugins/api.dart';

/* 모바일 광고 */
import '../../plugins/admob.dart';

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

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

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

class _IdFindingPageState extends State<IdFindingPage> {
  final TextEditingController nicknameController = TextEditingController();
  final TextEditingController emailController = TextEditingController();

  String nicknameErrorMessage = '';
  /* 닉네임 오류 메시지 */
  String emailErrorMessage = '';
  /* 이메일 오류 메시지 */
  String foundIdMessage = '';
  /* 찾은 ID 안내 메시지 */
  String authId = '';

  Future<void> _findId(String nickname, String email) async {
    /* ID 찾기 요청 처리 */

    // Show loading indicator (로딩 인디케이터 표시)
    showDialog(
      context: context,
      barrierDismissible: false, 
      builder: (BuildContext context) {
        return const Center(child: CircularProgressIndicator());
      },
    );

    try {
      final serverResponse = await Api.serverRequest(uri: '/user/find/id', body: {
              'nickname': nickname,
              'user_email': email,
            });
      Navigator.of(context).pop();

      if (serverResponse == null) {
        showResponseDialog(
          context, 
          'Find ID Failed' /* ID 찾기 실패 */, 
          'No response from server.' /* 서버 응답이 없습니다. */
        );
      }
      
      if (serverResponse['result'] == 'OK') {
        // Reset messages (오류 메시지, ID 메시지 등)
        setState(() {
          nicknameErrorMessage = '';
          emailErrorMessage = '';
          foundIdMessage = '';
        });

        final serverResponse1 = serverResponse['response'];

        if (serverResponse1['result'] == 'OK') {
          await showResponseDialog(
            context, 
            'Find ID Success' /* ID 찾기 성공 */, 
            'Your ID has been successfully found.' 
            /* ID가 찾아졌습니다. */
          );
          /* ID 찾기 성공 시 */
          setState(() {
            foundIdMessage = 'Your ID is ${serverResponse1['data']['user_id']}.'
                /* 당신의 ID는 ${serverResponse1['data']['user_id']} 입니다 */;
            authId = serverResponse1['data']['auth'];
          });
        } else {
          if (serverResponse1['response_info']['msg_title'] == 'Nickname Check') /* "닉네임 확인" */ {
            setState(() {
              nicknameErrorMessage = 'Please check your nickname again.'
                  /* 닉네임을 다시 확인해주세요 */;
            });
          } else if (serverResponse1['response_info']['msg_title'] == 'Email Check') /* "이메일 확인" */ {
            setState(() {
              emailErrorMessage = 'Please check your email again.'
                  /* 이메일을 다시 확인해주세요 */;
            });
          } else {
            showResponseDialog(
              context, 
              'Find ID Failed' /* ID 찾기 실패 */, 
              'Failed to find ID.' /* ID를 찾을 수 없습니다. */
            );
          }
        }
      } else {
        showResponseDialog(
          context, 
          'Find ID Failed' /* ID 찾기 실패 */, 
          'Failed to find ID.' /* ID를 찾을 수 없습니다. */
        );
      }
    } catch (e) {
      Navigator.of(context).pop();
      showResponseDialog(
        context, 
        'Error' /* 오류 */, 
        'Request failed. Please contact the administrator.'
        /* 요청이 실패했습니다. 관리자에게 문의해주세요. */
      );
    }
  }

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

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

  Future<void> _findAllId() async {
    /* ID 전체 찾기 요청 처리 */

    // Show loading indicator (로딩 인디케이터 표시)
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return const Center(child: CircularProgressIndicator());
      },
    );

    try {
      final serverResponse = await Api.serverRequest(uri: '/user/find/id/full', body: {'auth': authId});
      Navigator.of(context).pop();

      if (serverResponse == null) {
        showResponseDialog(
          context, 
          'Find All IDs Failed' /* ID 전체 찾기 실패 */, 
          'No response from server.' /* 서버 응답이 없습니다. */
        );
      }
      
      if (serverResponse['result'] == 'OK') {
        final serverResponse1 = serverResponse['response'];
        if (serverResponse1['result'] == 'OK') {
          // 성공
          showResponseDialog(
            context, 
            'Find All IDs Success' /* ID 전체 찾기 성공 */, 
            'We have sent all IDs to your email.'
            /* 이메일로 전체 ID를 발송했습니다. */
          );
        } else {
          showResponseDialog(
            context, 
            serverResponse1['response_info']['msg_title'] /* ID 전체 찾기 실패 */, 
            serverResponse1['response_info']['msg_content'] /* 전체 ID를 찾을 수 없습니다. */
          );
        }
      } else {
        showResponseDialog(
          context, 
          'Find All IDs Failed' /* ID 전체 찾기 실패 */, 
          'Failed to find all IDs.' /* 전체 ID를 찾을 수 없습니다. */
        );
      }
    } catch (e) {
      Navigator.of(context).pop();
      showResponseDialog(
        context, 
        'Error' /* 오류 */, 
        'Request failed. Please contact the administrator.'
        /* 요청이 실패했습니다. 관리자에게 문의해주세요. */
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('ALL SCORE', style: TextStyle(color: Colors.white)),
        backgroundColor: Colors.black,
        leading: IconButton(
          icon: const Icon(Icons.chevron_left, color: Colors.white),
          onPressed: () => Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (_) => const LoginPage()), (route) => false),
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              if (foundIdMessage.isEmpty) ...[
                const Text(
                  'Find ID'
                  /* ID 찾기 */,
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                    color: Colors.black,
                  ),
                ),
                const SizedBox(height: 32),
                TextField(
                  controller: nicknameController,
                  decoration: InputDecoration(
                    labelText: 'Nickname'
                    /* 닉네임 */,
                    labelStyle: const TextStyle(color: Colors.black),
                    border: const OutlineInputBorder(),
                    focusedBorder: const OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.black, width: 2.0),
                    ),
                  ),
                ),
                if (nicknameErrorMessage.isNotEmpty)
                  Padding(
                    padding: const EdgeInsets.only(top: 8.0),
                    child: Text(
                      nicknameErrorMessage,
                      style: const TextStyle(color: Colors.red),
                    ),
                  ),
                const SizedBox(height: 16),
                TextField(
                  controller: emailController,
                  decoration: InputDecoration(
                    labelText: 'Email'
                    /* 이메일 */,
                    labelStyle: const TextStyle(color: Colors.black),
                    border: const OutlineInputBorder(),
                    focusedBorder: const OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.black, width: 2.0),
                    ),
                  ),
                ),
                if (emailErrorMessage.isNotEmpty)
                  Padding(
                    padding: const EdgeInsets.only(top: 8.0),
                    child: Text(
                      emailErrorMessage,
                      style: const TextStyle(color: Colors.red),
                    ),
                  ),
                const SizedBox(height: 16),
                ElevatedButton(
                  onPressed: () {
                    _findId(nicknameController.text, emailController.text);
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.black,
                    foregroundColor: Colors.white,
                  ),
                  child: const Text('Find ID'
                    /* ID 찾기 */),
                ),
              ] else ...[
                // ID 찾기 성공 시 메시지
                Text(
                  foundIdMessage,
                  style: const TextStyle(fontSize: 20, color: Colors.black),
                ),
                const SizedBox(height: 16),
                ElevatedButton(
                  onPressed: () {
                    _findAllId(); 
                    /* ID 전체 찾기 버튼 */
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.black,
                    foregroundColor: Colors.white,
                  ),
                  child: const Text('Find All IDs'
                    /* ID 전체 찾기 */),
                ),
              ],
              const SizedBox(height: 16),
              TextButton(
                onPressed: () {
                  Navigator.pop(context);
                  /* 로그인 페이지로 이동 */
                },
                child: const Text('Login'
                  /* 로그인 */,
                  style: TextStyle(color: Colors.black)),
              ),
              TextButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const PwFindingPage()),
                  );
                },
                child: const Text('Find PW'
                  /* PW 찾기 */,
                  style: TextStyle(color: Colors.black)),
              ),
              TextButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const SignUpPage()),
                  );
                },
                child: const Text('Sign Up'
                  /* 회원가입 */,
                  style: TextStyle(color: Colors.black)),
              ),
            ],
          ),
        ),
      ),

      bottomNavigationBar: AdBannerWidget()
      /* (3) 하단 광고 영역 */,
    );
  }
}
