import 'package:chepuhagram/presentation/screens/account_settings_screen.dart';
import 'package:chepuhagram/presentation/screens/login_screen.dart';
import 'package:chepuhagram/presentation/screens/privacy_settings_menu_screen.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '/logic/auth_provider.dart';
import '/core/theme_manager.dart';
import 'package:package_info_plus/package_info_plus.dart';

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

  @override
  State<SettingsScreen> createState() => _SettingsScreenState();
}

class _SettingsScreenState extends State<SettingsScreen> {
  String? versionCode;

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

  void _loadVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    if (mounted) {
      setState(() {
        versionCode = packageInfo.version;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final themeProv = context.watch<ThemeProvider>();
    final authProv = context.watch<AuthProvider>();

    final accountEmail = authProv.email?.isNotEmpty == true
        ? authProv.email!
        : authProv.username?.isNotEmpty == true
        ? '@${authProv.username!}'
        : 'Не указано';

    final username = authProv.username;
    final displayName = authProv.displayName;
    final initials = (displayName.isNotEmpty ? displayName : (username ?? 'U'))
        .trim()
        .split(RegExp(r'\s+'))
        .where((p) => p.isNotEmpty)
        .take(2)
        .map((p) => p[0].toUpperCase())
        .join();

    return Scaffold(
      appBar: AppBar(title: const Text("Настройки")),
      body: Column(
        children: [
          // Секция Профиля
          UserAccountsDrawerHeader(
            accountName: Text(
              authProv.displayName,
              style: TextStyle(color: Theme.of(context).colorScheme.onSurface),
            ),
            accountEmail: Text(
              accountEmail,
              style: TextStyle(color: Theme.of(context).colorScheme.onSurface),
            ),
            currentAccountPicture: CircleAvatar(
              child: Text(
                initials.isEmpty ? 'U' : initials,
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Theme.of(context).colorScheme.onSurface,
                ),
              ),
            ),
            decoration: const BoxDecoration(color: Colors.transparent),
          ),

          const Divider(),
          ListTile(
            leading: const Icon(Icons.person_outline),
            title: const Text('Аккаунт'),
            subtitle: const Text('Имя, телефон, почта, информация о себе'),
            trailing: const Icon(Icons.chevron_right),
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (_) => const AccountSettingsScreen(),
                ),
              );
            },
          ),
          const Divider(),
          ListTile(
            leading: const Icon(Icons.shield_outlined),
            title: const Text('Конфиденциальность'),
            subtitle: const Text('Безопасность и видимость данных профиля'),
            trailing: const Icon(Icons.chevron_right),
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (_) => const PrivacySettingsMenuScreen(),
                ),
              );
            },
          ),
          const Divider(),

          SwitchListTile(
            secondary: const Icon(Icons.dark_mode),
            title: const Text("Ночной режим"),
            value: themeProv.themeMode == ThemeMode.dark,
            onChanged: (val) => themeProv.toggleTheme(val),
          ),

          // Выбор цвета акцента
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Icon(
                      Icons.palette_outlined,
                      color: Theme.of(context).colorScheme.onSurface,
                    ),
                    SizedBox(width: 10),
                    const Text("Цвет темы"),
                    Spacer(),
                    _colorCircle(context, const Color(0xFF24A1DE), themeProv),
                    _colorCircle(context, const Color(0xFF3E8E7E), themeProv),
                    _colorCircle(context, const Color(0xFF8E3E7E), themeProv),
                    _colorCircle(context, const Color(0xFFFF9800), themeProv),
                    _colorCircle(context, const Color(0xFFF44336), themeProv),
                  ],
                ),
              ],
            ),
          ),

          const Divider(),

          // Выход
          ListTile(
            leading: const Icon(Icons.exit_to_app, color: Colors.red),
            title: const Text(
              "Выйти из аккаунта",
              style: TextStyle(color: Colors.red),
            ),
            onTap: () async {
              await authProv.logout();
              if (context.mounted) {
                Navigator.pushReplacement(
                  context,
                  MaterialPageRoute(builder: (_) => const LoginScreen()),
                );
              }
            },
          ),
          const Spacer(),
          Center(
            child: Text(
              "Chepuhagram for Android v$versionCode",
              style: TextStyle(color: Colors.grey, fontSize: 12),
            ),
          ),
          const Center(
            child: Text(
              "Made by ArturKarasevich",
              style: TextStyle(color: Colors.grey, fontSize: 12),
            ),
          ),
          const Spacer(),
        ],
      ),
    );
  }

  Widget _colorCircle(BuildContext context, Color color, ThemeProvider prov) {
    bool isSelected = prov.accentColor == color;
    return GestureDetector(
      onTap: () => prov.updateAccentColor(color),
      child: Container(
        padding: const EdgeInsets.all(2),
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          border: Border.all(
            color: isSelected ? color : Colors.transparent,
            width: 2,
          ),
        ),
        child: CircleAvatar(backgroundColor: color, radius: 15),
      ),
    );
  }
}
