import 'package:flutter/material.dart';
import '../services/auth_service.dart';
import 'welcome_screen.dart';
import 'notice_screen.dart';
import '../data/terms_data.dart';

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

  @override
  State<MyInfoScreen> createState() => _MyInfoScreenState();
}

class _MyInfoScreenState extends State<MyInfoScreen> {
  final AuthService _authService = AuthService();
  Map<String, dynamic>? _userInfo;
  bool _isLoading = true;

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

  Future<void> _fetchUserInfo() async {
    try {
      final info = await _authService.getUserInfo();
      if (mounted) {
        setState(() {
          _userInfo = info;
        });
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('정보를 불러올 수 없습니다. 잠시 후 다시 시도해주세요.')),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  Future<void> _handleLogout() async {
    await _authService.signOut();
    if (mounted) {
      Navigator.of(context).pushAndRemoveUntil(
        MaterialPageRoute(builder: (context) => const WelcomeScreen()),
        (route) => false,
      );
    }
  }

  Future<void> _handleWithdraw() async {
    bool? confirm = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('회원 탈퇴'),
        content: const Text('정말로 탈퇴하시겠습니까?\n모든 데이터가 삭제되며 복구할 수 없습니다.'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('취소'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('탈퇴하기', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );

    if (confirm == true) {
      if (!mounted) return;
      final success = await _authService.withdrawAccount();
      if (success && mounted) {
        Navigator.of(context).pushAndRemoveUntil(
          MaterialPageRoute(builder: (context) => const WelcomeScreen()),
          (route) => false,
        );
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('탈퇴 처리에 실패했습니다. 다시 시도해주세요.')),
          );
        }
      }
    }
  }

  // 통합 약관 모달 보여주기
  void _showAllTermsModal(BuildContext context) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) {
        return DraggableScrollableSheet(
          initialChildSize: 0.85,
          minChildSize: 0.5,
          maxChildSize: 0.95,
          builder: (_, controller) {
            return Container(
              decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
              ),
              padding: const EdgeInsets.fromLTRB(20, 10, 20, 20),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 핸들 바
                  Center(
                    child: Container(
                      width: 40,
                      height: 4,
                      margin: const EdgeInsets.only(bottom: 20, top: 10),
                      decoration: BoxDecoration(
                        color: Colors.grey[300],
                        borderRadius: BorderRadius.circular(2),
                      ),
                    ),
                  ),

                  // 헤더
                  const Row(
                    children: [
                      Icon(Icons.description, size: 24, color: Colors.black87),
                      SizedBox(width: 8),
                      Text(
                        '서비스 이용 약관 전체보기',
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                          fontFamily: 'SCDream',
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 20),

                  // 스크롤 가능한 본문 (모든 약관 내용 통합)
                  Expanded(
                    child: ListView.separated(
                      controller: controller, // 드래그 가능한 스크롤 컨트롤러 연결
                      itemCount: TermsData.terms.length,
                      separatorBuilder: (context, index) => const Padding(
                        padding: EdgeInsets.symmetric(vertical: 20),
                        child: Divider(color: Color(0xFFEEEEEE), thickness: 1),
                      ),
                      itemBuilder: (context, index) {
                        final term = TermsData.terms[index];
                        return Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              term['title']!,
                              style: const TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: Color(0xFFFF7500), // 강조색
                                fontFamily: 'SCDream',
                              ),
                            ),
                            const SizedBox(height: 10),
                            Text(
                              term['content']!,
                              style: const TextStyle(
                                fontSize: 14,
                                height: 1.6,
                                color: Colors.black87,
                                fontFamily: 'SCDream',
                              ),
                            ),
                          ],
                        );
                      },
                    ),
                  ),

                  const SizedBox(height: 10),
                  // 닫기 버튼
                  SizedBox(
                    width: double.infinity,
                    height: 52,
                    child: ElevatedButton(
                      onPressed: () => Navigator.pop(context),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFFFF7500),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                        elevation: 0,
                      ),
                      child: const Text(
                        '닫기',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                          fontFamily: 'SCDream',
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return const Scaffold(body: Center(child: CircularProgressIndicator()));
    }

    return Scaffold(
      backgroundColor: Colors.white,
      body: _userInfo == null
          ? const Center(child: Text('정보를 불러올 수 없습니다.'))
          : SafeArea(
              child: Column(
                children: [
                  Expanded(
                    child: SingleChildScrollView(
                      padding: const EdgeInsets.all(20),
                      child: Column(
                        children: [
                          Container(
                            width: double.infinity,
                            padding: const EdgeInsets.all(20),
                            decoration: BoxDecoration(
                              color: Colors.grey[100],
                              borderRadius: BorderRadius.circular(16),
                            ),
                            child: Row(
                              children: [
                                const CircleAvatar(
                                  radius: 35,
                                  backgroundColor: Colors.grey,
                                  child: Icon(
                                    Icons.person,
                                    size: 50,
                                    color: Colors.white,
                                  ),
                                ),
                                const SizedBox(width: 20),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      _userInfo!['nickname'] ?? '이름 없음',
                                      style: const TextStyle(
                                        fontFamily: 'SCDream',
                                        fontSize: 20,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                    const SizedBox(height: 8),
                                    Text(
                                      _userInfo!['email'] ?? '이메일 없음',
                                      style: TextStyle(
                                        fontFamily: 'SCDream',
                                        fontSize: 14,
                                        color: Colors.grey[600],
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                          const SizedBox(height: 30),
                          _buildMenuItem(
                            title: '공지사항',
                            icon: Icons.campaign_outlined,
                            onTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => const NoticeScreen(),
                                ),
                              );
                            },
                          ),
                          const SizedBox(height: 10),
                          _buildMenuItem(
                            title: '서비스 이용 약관',
                            icon: Icons.description_outlined,
                            onTap: () => _showAllTermsModal(context),
                          ),
                          const SizedBox(height: 10),
                          _buildMenuItem(
                            title: '버전 정보',
                            icon: Icons.info_outline,
                            trailingText: '1.0.0',
                            onTap: () {},
                          ),
                          // 회원 탈퇴 버튼 removed from here
                        ],
                      ),
                    ),
                  ),

                  // 하단 고정 영역 (로그아웃 & 탈퇴)
                  Padding(
                    padding: const EdgeInsets.fromLTRB(20, 0, 20, 30),
                    child: Column(
                      children: [
                        // 로그아웃 버튼 (회원탈퇴 위로 이동)
                        _buildMenuItem(
                          title: '로그아웃',
                          icon: Icons.logout,
                          onTap: _handleLogout,
                        ),

                        const SizedBox(height: 10),

                        // 회원 탈퇴 버튼
                        _buildMenuItem(
                          title: '회원 탈퇴',
                          icon: Icons.person_off_outlined,
                          isDestructive: true,
                          onTap: _handleWithdraw,
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
    );
  }

  Widget _buildMenuItem({
    required String title,
    required IconData icon,
    VoidCallback? onTap, // onTap을 nullable로 변경
    bool isDestructive = false,
    String? trailingText, // 뒤에 텍스트를 표시할 수 있도록 추가
  }) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: Colors.grey[200]!),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: onTap,
          borderRadius: BorderRadius.circular(12),
          child: Padding(
            padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 20),
            child: Row(
              children: [
                Icon(icon, color: isDestructive ? Colors.red : Colors.black54),
                const SizedBox(width: 16),
                Expanded(
                  child: Text(
                    title,
                    style: TextStyle(
                      fontFamily: 'SCDream',
                      fontSize: 16,
                      fontWeight: FontWeight.w500, // Medium
                      color: isDestructive ? Colors.red : Colors.black,
                    ),
                  ),
                ),
                if (trailingText != null)
                  Text(
                    trailingText,
                    style: const TextStyle(
                      fontFamily: 'SCDream',
                      fontSize: 14,
                      color: Colors.grey,
                      fontWeight: FontWeight.bold,
                    ),
                  )
                else
                  Icon(
                    Icons.arrow_forward_ios,
                    size: 16,
                    color: isDestructive ? Colors.red : Colors.grey,
                  ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
