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:chepuhagram/presentation/screens/appearance_settings_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';
import 'package:image_picker/image_picker.dart';
import 'dart:io';

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

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

class _SettingsScreenState extends State<SettingsScreen> {
  String? versionCode;
  final ImagePicker _picker = ImagePicker();

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

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

  Future<void> _pickAvatar() async {
    final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      final success = await context.read<AuthProvider>().updateAvatar(image.path);
      if (!success) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Ошибка загрузки аватарки')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    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: GestureDetector(
              onTap: _pickAvatar,
              child: SizedBox(
                width: 80,
                height: 80,
                child: Stack(
                  children: [
                    authProv.avatarUrl != null
                        ? CircleAvatar(
                            radius: 40,
                            backgroundImage: NetworkImage(authProv.avatarUrl!),
                          )
                        : authProv.avatarPath != null
                            ? CircleAvatar(
                                radius: 40,
                                backgroundImage: FileImage(File(authProv.avatarPath!)),
                              )
                            : CircleAvatar(
                                radius: 40,
                                child: Text(
                                  initials.isEmpty ? 'U' : initials,
                                  style: TextStyle(
                                    fontSize: 20,
                                    fontWeight: FontWeight.bold,
                                    color: Theme.of(context).colorScheme.onSurface,
                                  ),
                                ),
                              ),
                    Positioned(
                      bottom: 0,
                      right: 0,
                      child: Container(
                        padding: const EdgeInsets.all(2),
                        decoration: BoxDecoration(
                          color: Theme.of(context).colorScheme.primary,
                          shape: BoxShape.circle,
                        ),
                        child: Icon(
                          Icons.camera_alt,
                          size: 16,
                          color: Theme.of(context).colorScheme.onPrimary,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            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(),
          ListTile(
            leading: const Icon(Icons.palette),
            title: const Text('Оформление'),
            subtitle: const Text('Тема, цвета, обои'),
            trailing: const Icon(Icons.chevron_right),
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (_) => const AppearanceSettingsScreen(),
                ),
              );
            },
          ),
          const Divider(),

          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(),
        ],
      ),
    );
  }
}
