import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:service_api/service_api.dart';
import 'package:url_launcher/url_launcher.dart'; 

class SettingsScreen extends StatelessWidget {
  const SettingsScreen({super.key});

  Future<void> _launchHomepage() async {
    final Uri url = Uri.parse('https://lunaticbum.kr'); 
    if (!await launchUrl(url, mode: LaunchMode.externalApplication)) {
      debugPrint('Could not launch $url');
    }
  }

  @override
  Widget build(BuildContext context) {
    final themeNotifier = context.watch<ThemeNotifier>();
    final sessionNotifier = context.watch<SessionNotifier>();

    return Scaffold(
      appBar: AppBar(
        title: const Text('설정'),
      ),
      body: ListView(
        children: [
          // 🔽 [수정] 계정 연동 섹션
          ListTile(
            leading: Icon(
              sessionNotifier.isGuest 
                ? Icons.person_outline 
                : Icons.person_rounded
            ),
            title: Text(
              sessionNotifier.isLoading
                ? '계정 정보 로딩 중...'
                : (sessionNotifier.isGuest
                  ? '게스트 계정'
                  : sessionNotifier.session?.userName ?? '로그인됨')
            ),
            subtitle: Text(
              sessionNotifier.isLoading
                ? ''
                : (sessionNotifier.isGuest
                  ? '진행 상황을 저장하려면 로그인하세요.'
                  : (sessionNotifier.session?.email ?? '소셜 계정'))
            ),
          ),
          
          if (!sessionNotifier.isLoading) 
            if (sessionNotifier.isGuest)
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                child: Row(
                  children: [
                    Expanded(
                      child: OutlinedButton.icon(
                        icon: const Icon(Icons.g_mobiledata), // (임시) Google 아이콘
                        label: const Text('Google 로그인'),
                        onPressed: () {
                          // 🔽 [수정] 로그인 함수 호출
                          sessionNotifier.login('google');
                        },
                      ),
                    ),
                    const SizedBox(width: 10),
                    Expanded(
                      child: OutlinedButton.icon(
                        icon: const Icon(Icons.apple),
                        label: const Text('Apple 로그인'),
                        onPressed: () {
                          // 🔽 [수정] 로그인 함수 호출
                          sessionNotifier.login('apple');
                        },
                      ),
                    ),
                  ],
                ),
              )
            else
              ListTile(
                title: const Text('로그아웃', style: TextStyle(color: Colors.red)),
                leading: const Icon(Icons.logout, color: Colors.red),
                onTap: () {
                  sessionNotifier.logout();
                },
              ),

          const Divider(),
          
          // --- 0. 다크 모드 토글 ---
          SwitchListTile(
            title: const Text('다크 모드'),
            secondary: const Icon(Icons.dark_mode_outlined),
            value: themeNotifier.isDarkMode, 
            onChanged: (newValue) {
              themeNotifier.toggleTheme(newValue);
            },
          ),
          
          const Divider(),

          // --- 1. 테마 선택 섹션 ---
          const Padding(
            padding: EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 8.0),
            child: Text(
              '앱 테마 색상',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
          ),
          
          ...appColors.entries.map((entry) {
            final String colorName = entry.key;
            final MaterialColor color = entry.value;

            return ListTile(
              leading: CircleAvatar(
                backgroundColor: color,
              ),
              title: Text(colorName),
              trailing: (themeNotifier.currentColor == color)
                  ? Icon(Icons.check, color: Theme.of(context).colorScheme.secondary) 
                  : null,
              onTap: () {
                themeNotifier.setTheme(colorName);
              },
            );
          }),

          const Divider(),

          // --- 2. 라이선스 정보 섹션 ---
          ListTile(
            leading: const Icon(Icons.description_outlined),
            title: const Text('오픈소스 라이선스'),
            onTap: () {
              showLicensePage(
                context: context,
                applicationName: '스도쿠 게임',
                applicationVersion: '1.0.0', 
                applicationIcon: const Icon(Icons.apps_rounded, size: 64),
              );
            },
          ),
          
          ListTile(
            leading: const Icon(Icons.info_outline),
            title: const Text('앱 정보'),
            onTap: () {
              showAboutDialog(
                context: context,
                applicationName: '스도쿠 게임',
                applicationVersion: '1.0.0',
                applicationIcon: const Icon(Icons.apps_rounded, size: 48),
                children: [
                  const SizedBox(height: 16),
                  InkWell(
                    onTap: _launchHomepage, 
                    child: Padding(
                      padding: const EdgeInsets.symmetric(vertical: 8.0), 
                      child: Text(
                        '© 2025 lunaticbum',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: Theme.of(context).colorScheme.primary,
                          decoration: TextDecoration.underline,
                        ),
                      ),
                    ),
                  ),
                ],
              );
            },
          ),
            
        ],
      ),
    );
  }
}