import 'dart:io';
import 'package:barber_app/features/services/presentation/pages/services_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:barber_app/core/theme/app_theme.dart';
import 'package:barber_app/core/constants/app_strings.dart';
import 'package:barber_app/core/database/database_service.dart';
import 'package:barber_app/features/auth/presentation/bloc/auth_bloc.dart';
import 'package:barber_app/features/auth/data/repositories/auth_repository.dart';
import 'package:barber_app/features/auth/presentation/pages/login_page.dart';
import 'package:barber_app/features/settings/data/models/settings_model.dart';

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

  @override
  State<SettingsPage> createState() => _SettingsPageState();
}

class _SettingsPageState extends State<SettingsPage> {
  final _authRepo = AuthRepository();
  SettingsModel? _settings;
  String? _logoPath;
  Color _selectedColor = AppColors.primaryColor;
  final _imagePicker = ImagePicker();
  final _appNameController = TextEditingController();

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

  @override
  void dispose() {
    _appNameController.dispose();
    super.dispose();
  }

  void _updateAppName(String name) async {
    final userId = DatabaseService.getCurrentUserId();
    if (userId != null && _settings != null) {
      final updated = _settings!.copyWith(appName: name);
      await DatabaseService.settingsBoxInstance.put(userId, updated);
      _loadSettings();
    }
  }

  void _showAppNameDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: AppColors.surface,
        title: const Text('Nome do Aplicativo'),
        content: TextField(
          controller: _appNameController,
          decoration: const InputDecoration(hintText: 'Digite o nome do app'),
          autofocus: true,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text(AppStrings.cancel),
          ),
          TextButton(
            onPressed: () {
              _updateAppName(_appNameController.text);
              Navigator.pop(context);
            },
            child: const Text('Salvar'),
          ),
        ],
      ),
    );
  }

  void _loadSettings() {
    final userId = DatabaseService.getCurrentUserId();
    if (userId != null) {
      _settings = DatabaseService.settingsBoxInstance.get(userId);
      if (_settings != null) {
        _logoPath = _settings!.logoPath;
        _selectedColor = Color(_settings!.primaryColorValue);
        _appNameController.text = _settings!.appName ?? 'Barber App';
      }
    }
    setState(() {});
  }

  Future<void> _pickLogo() async {
    final image = await _imagePicker.pickImage(source: ImageSource.gallery);
    if (image == null) return;

    // Salva a imagem localmente
    final appDir = await getApplicationDocumentsDirectory();
    final fileName = 'logo_${DateTime.now().millisecondsSinceEpoch}.png';
    final savedImage = await File(image.path).copy('${appDir.path}/$fileName');

    final userId = DatabaseService.getCurrentUserId();
    if (userId != null && _settings != null) {
      final updated = _settings!.copyWith(logoPath: savedImage.path);
      await DatabaseService.settingsBoxInstance.put(userId, updated);
      _loadSettings();
    }
  }

  void _showColorPicker() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: AppColors.surface,
        title: const Text('Escolha uma cor'),
        content: SizedBox(
          width: 280,
          child: Wrap(
            spacing: 12,
            runSpacing: 12,
            children: [
              _buildColorOption(const Color(0xFFD4AF37)), // Dourado
              _buildColorOption(const Color(0xFF4CAF50)), // Verde
              _buildColorOption(const Color(0xFF2196F3)), // Azul
              _buildColorOption(const Color(0xFF9C27B0)), // Roxo
              _buildColorOption(const Color(0xFFFF5722)), // Laranja
              _buildColorOption(const Color(0xFFE91E63)), // Rosa
              _buildColorOption(const Color(0xFF00BCD4)), // Ciano
              _buildColorOption(const Color(0xFFFF9800)), // Amber
              _buildColorOption(const Color(0xFF607D8B)), // Cinza azulado
              _buildColorOption(const Color(0xFF795548)), // Marrom
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildColorOption(Color color) {
    final isSelected = _selectedColor.toARGB32() == color.toARGB32();
    return GestureDetector(
      onTap: () async {
        setState(() => _selectedColor = color);
        AppColors.updatePrimaryColor(color);

        final userId = DatabaseService.getCurrentUserId();
        if (userId != null && _settings != null) {
          final updated = _settings!.copyWith(
            primaryColorValue: color.toARGB32(),
          );
          await DatabaseService.settingsBoxInstance.put(userId, updated);
        }

        if (mounted) Navigator.pop(context);
        setState(() {});
      },
      child: Container(
        width: 48,
        height: 48,
        decoration: BoxDecoration(
          color: color,
          shape: BoxShape.circle,
          border: isSelected ? Border.all(color: Colors.white, width: 3) : null,
          boxShadow: [
            BoxShadow(
              color: color.withValues(alpha: 0.4),
              blurRadius: 8,
              spreadRadius: 1,
            ),
          ],
        ),
        child: isSelected ? const Icon(Icons.check, color: Colors.white) : null,
      ),
    );
  }

  void _confirmLogout() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: AppColors.surface,
        title: const Text('Sair'),
        content: const Text('Deseja realmente sair do aplicativo?'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text(AppStrings.cancel),
          ),
          TextButton(
            onPressed: () {
              context.read<AuthBloc>().add(AuthLogoutRequested());
              Navigator.of(context).pushAndRemoveUntil(
                MaterialPageRoute(builder: (_) => const LoginPage()),
                (route) => false,
              );
            },
            child: Text(
              AppStrings.logout,
              style: TextStyle(color: AppColors.error),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final user = _authRepo.getCurrentUser();

    return Scaffold(
      appBar: AppBar(title: const Text(AppStrings.settings)),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(24),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Perfil
            Center(
              child: Column(
                children: [
                  GestureDetector(
                    onTap: _pickLogo,
                    child: Container(
                      width: 100,
                      height: 100,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: AppColors.surface,
                        border: Border.all(color: _selectedColor, width: 3),
                        image:
                            _logoPath != null && File(_logoPath!).existsSync()
                            ? DecorationImage(
                                image: FileImage(File(_logoPath!)),
                                fit: BoxFit.cover,
                              )
                            : null,
                      ),
                      child: _logoPath == null || !File(_logoPath!).existsSync()
                          ? Icon(
                              Icons.content_cut,
                              size: 40,
                              color: _selectedColor,
                            )
                          : null,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    'Toque para alterar logo',
                    style: TextStyle(
                      fontSize: 12,
                      color: AppColors.textSecondary,
                    ),
                  ),
                  const SizedBox(height: 16),
                  Text(
                    user?.barberShopName ?? '',
                    style: const TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                      color: AppColors.textPrimary,
                    ),
                  ),
                  Text(
                    user?.barberName ?? '',
                    style: TextStyle(color: _selectedColor),
                  ),
                  Text(
                    user?.email ?? '',
                    style: const TextStyle(
                      fontSize: 12,
                      color: AppColors.textSecondary,
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 32),

            // Personalização
            const Text(
              'Personalização',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
                color: AppColors.textPrimary,
              ),
            ),
            const SizedBox(height: 16),

            _buildSettingsTile(
              icon: Icons.content_cut, // Icone de tesoura
              title: 'Meus Serviços',
              subtitle: 'Gerenciar catálogo de serviços e preços',
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (_) => const ServicesPage()),
                );
              },
            ),

            _buildSettingsTile(
              icon: Icons.palette_outlined,
              title: AppStrings.primaryColor,
              subtitle: 'Altere a cor tema do app',
              trailing: Container(
                width: 32,
                height: 32,
                decoration: BoxDecoration(
                  color: _selectedColor,
                  shape: BoxShape.circle,
                ),
              ),
              onTap: _showColorPicker,
            ),

            _buildSettingsTile(
              icon: Icons.image_outlined,
              title: AppStrings.changeLogo,
              subtitle: 'Personalize com a logo da barbearia',
              onTap: _pickLogo,
            ),

            _buildSettingsTile(
              icon: Icons.label_important_outline,
              title: 'Nome do App',
              subtitle: 'Altera o nome exibido no app',
              trailing: Text(
                _settings?.appName ?? 'Barber App',
                style: TextStyle(color: AppColors.textSecondary, fontSize: 13),
              ),
              onTap: _showAppNameDialog,
            ),

            _buildSettingsTile(
              icon: Icons.dark_mode_outlined,
              title: 'Tema Escuro',
              subtitle: 'Alternar entre modo claro e escuro',
              trailing: Switch(
                value: _settings?.isDark ?? true,
                activeThumbColor: _selectedColor,
                onChanged: (value) async {
                  final userId = DatabaseService.getCurrentUserId();
                  if (userId != null && _settings != null) {
                    final updated = _settings!.copyWith(isDark: value);
                    await DatabaseService.settingsBoxInstance.put(
                      userId,
                      updated,
                    );
                    // O Listener no main.dart vai reconstruir o app
                    _loadSettings();
                  }
                },
              ),
            ),

            const SizedBox(height: 24),

            // Conta
            const Text(
              'Conta',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
                color: AppColors.textPrimary,
              ),
            ),
            const SizedBox(height: 16),

            _buildSettingsTile(
              icon: Icons.logout,
              title: AppStrings.logout,
              subtitle: 'Sair da sua conta',
              iconColor: AppColors.error,
              onTap: _confirmLogout,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSettingsTile({
    required IconData icon,
    required String title,
    required String subtitle,
    Widget? trailing,
    Color? iconColor,
    VoidCallback? onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        margin: const EdgeInsets.only(bottom: 12),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: AppColors.surface,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: AppColors.surfaceLight),
        ),
        child: Row(
          children: [
            Container(
              width: 44,
              height: 44,
              decoration: BoxDecoration(
                color: (iconColor ?? _selectedColor).withValues(alpha: 0.1),
                borderRadius: BorderRadius.circular(10),
              ),
              child: Icon(icon, color: iconColor ?? _selectedColor),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: const TextStyle(
                      fontWeight: FontWeight.w600,
                      color: AppColors.textPrimary,
                    ),
                  ),
                  Text(
                    subtitle,
                    style: const TextStyle(
                      fontSize: 12,
                      color: AppColors.textSecondary,
                    ),
                  ),
                ],
              ),
            ),
            trailing ??
                Icon(
                  Icons.arrow_forward_ios,
                  size: 16,
                  color: AppColors.textSecondary,
                ),
          ],
        ),
      ),
    );
  }
}
