import 'package:flutter/material.dart';
import 'package:http/http.dart' as http; // http 패키지 임포트
import 'dart:convert';
import 'dart:convert' show utf8;
import 'login_page.dart'; // 로그인 페이지 임포트
import 'signup_page.dart'; // 회원가입 페이지 임포트
import 'id_finding_page.dart'; // ID 찾기 페이지 임포트
import '../../dialogs/response_dialog.dart';
import '../../plugins/api.dart';

// Mobile ads (모바일 광고)
import '../../plugins/admob.dart';

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

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

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

class _PwFindingPageState extends State<PwFindingPage> {
  final TextEditingController idController = TextEditingController(); 
  final TextEditingController emailController = TextEditingController();

  String emailErrorMessage = '';
  String idErrorMessage = '';

  Future<void> _findPassword(String id, String email) async {
    /* PW 찾기 요청 처리 */
    // 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/password', body: {'user_id': id, 'user_email': email});
      Navigator.of(context).pop();

      if (serverResponse == null) {
        showResponseDialog(
          context, 
          'Find Password Failed' /* PW 찾기 실패 */, 
          'No response from server.' /* 서버 응답이 없습니다. */
        );
      }

      if (serverResponse['result'] == 'OK') {
        final serverResponse1 = serverResponse['response'];

        // Reset error messages (오류 메시지 초기화)
        setState(() {
          emailErrorMessage = '';
          idErrorMessage = '';
        });

        if (serverResponse1['result'] == 'OK') {
          // 성공
          showResponseDialog(
            context, 
            'Find Password Success' /* PW 찾기 성공 */, 
            'An interim password has been sent to your email.' /* 임시 비밀번호가 입력하신 이메일로 발송되었습니다. */
          );
        } else {
          if (serverResponse1['response_info']['msg_title'] == 'ID Check') {
            setState(() {
              idErrorMessage = 'Please check your ID again.' 
                  /* 아이디를 다시 확인해주세요 */;
            });
          } else if (serverResponse1['response_info']['msg_title'] == 'Email Check') {
            setState(() {
              emailErrorMessage = 'Please check your email again.' 
                  /* 이메일을 다시 확인해주세요 */;
            });
          } else {
            showResponseDialog(
              context, 
              serverResponse1['response_info']['msg_title'] /* PW 찾기 실패 */, 
              serverResponse1['response_info']['msg_content'] /* 비밀번호를 찾을 수 없습니다. */
            );
          }
        }
      } else {
        showResponseDialog(
          context, 
          'Find Password Failed' /* PW 찾기 실패 */, 
          'Failed to find password.' /* 비밀번호를 찾을 수 없습니다. */
        );
      }
    } 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();
  }

  @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: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              'Find Password' 
              /* PW 찾기 */,
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: Colors.black),
            ),
            const SizedBox(height: 32),
            TextField(
              controller: idController, 
              decoration: const InputDecoration(
                labelText: 'ID' 
                /* ID */,
                labelStyle: TextStyle(color: Colors.black),
                border: OutlineInputBorder(),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Colors.black, width: 2.0),
                ),
              ),
            ),
            if (idErrorMessage.isNotEmpty)
              Padding(
                padding: const EdgeInsets.only(top: 8.0),
                child: Text(
                  idErrorMessage,
                  style: const TextStyle(color: Colors.red),
                ),
              ),
            const SizedBox(height: 16),
            TextField(
              controller: emailController, 
              decoration: const InputDecoration(
                labelText: 'Email' 
                /* 이메일 */,
                labelStyle: TextStyle(color: Colors.black),
                border: OutlineInputBorder(),
                focusedBorder: 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: () {
                /* PW 찾기 요청 */
                _findPassword(idController.text, emailController.text);
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.black,
                foregroundColor: Colors.white,
              ),
              child: const Text('Find Password' 
                  /* PW 찾기 */),
            ),
            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 IdFindingPage()),
                );
              },
              child: const Text('Find ID' /* ID 찾기 */, 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) 하단 광고 영역 */
    );
  }
}
