import 'package:drift/drift.dart' hide Column;
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:slrpg_app/l10n/app_localizations.dart';

import '../../../../core/theme/app_theme.dart';
import '../../../../shared/data/repositories/user_repository.dart';
import '../../../../shared/data/local/app_database.dart';
import '../../../gamification/domain/entities/avatar_config.dart';
import '../../../gamification/presentation/widgets/avatar_editor.dart';
import '../../../gamification/presentation/widgets/avatar_renderer.dart';
import '../../../gamification/domain/entities/item_catalog.dart';
import '../../../../shared/domain/logic/wendler_calculator.dart';

class ProfileScreen extends ConsumerStatefulWidget {
  const ProfileScreen({super.key});

  @override
  ConsumerState<ProfileScreen> createState() => _ProfileScreenState();
}

class _ProfileScreenState extends ConsumerState<ProfileScreen> {
  bool _isLoading = false;
  double _currentBodyweight = 80.0;
  bool _hasChanges = false;
  UserCollection? _user;
  AvatarConfig? _tempAvatarConfig;

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

  Future<void> _loadUser() async {
    final user = await ref.read(userRepositoryProvider).getLocalUser();
    if (user != null && mounted) {
      setState(() {
        _user = user;
        _currentBodyweight = user.currentBodyweight;
      });
    }
  }

  Future<void> _saveBodyweight() async {
    setState(() => _isLoading = true);
    try {
      await ref
          .read(userRepositoryProvider)
          .updateBodyweight(_currentBodyweight);

      if (_user != null) {
        _user = _user!.copyWith(currentBodyweight: _currentBodyweight);
      }

      if (mounted) {
        setState(() => _hasChanges = false);
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Bodyweight updated')),
        );
      }
    } finally {
      if (mounted) setState(() => _isLoading = false);
    }
  }

  void _showChangePasswordDialog() {
    final oldPassCtrl = TextEditingController();
    final newPassCtrl = TextEditingController();
    final confirmPassCtrl = TextEditingController();
    final formKey = GlobalKey<FormState>();

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Change Password'),
        content: Form(
          key: formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextFormField(
                controller: oldPassCtrl,
                obscureText: true,
                decoration: const InputDecoration(labelText: 'Old Password'),
                validator: (v) => v?.isEmpty == true ? 'Required' : null,
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: newPassCtrl,
                obscureText: true,
                decoration: const InputDecoration(labelText: 'New Password'),
                validator: (v) => (v?.length ?? 0) < 8 ? 'Min 8 chars' : null,
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: confirmPassCtrl,
                obscureText: true,
                decoration: const InputDecoration(labelText: 'Confirm New'),
                validator: (v) => v != newPassCtrl.text ? 'Mismatch' : null,
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('CANCEL'),
          ),
          ElevatedButton(
            onPressed: () async {
              if (formKey.currentState!.validate()) {
                Navigator.pop(context);
                setState(() => _isLoading = true);
                try {
                  await ref.read(userRepositoryProvider).changePassword(
                        oldPassCtrl.text,
                        newPassCtrl.text,
                      );
                  if (mounted) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                          content: Text('Password changed successfully')),
                    );
                  }
                } catch (e) {
                  if (mounted) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                          content: Text('Error: $e'),
                          backgroundColor: AppTheme.errorColor),
                    );
                  }
                } finally {
                  if (mounted) setState(() => _isLoading = false);
                }
              }
            },
            child: const Text('UPDATE'),
          ),
        ],
      ),
    );
  }

  void _showBackgroundSelector() {
    final currentLevel = _user?.level ?? 1;
    final currentConfig = _user?.avatarConfig != null
        ? AvatarConfig.fromJson(_user!.avatarConfig!)
        : const AvatarConfig();

    showModalBottomSheet(
      context: context,
      backgroundColor: AppTheme.surfaceColor,
      builder: (context) => Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Padding(
            padding: const EdgeInsets.all(16),
            child: Text('Select Scenery',
                style: Theme.of(context).textTheme.titleLarge),
          ),
          SizedBox(
            height: 200,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              padding: const EdgeInsets.symmetric(horizontal: 16),
              itemCount: ItemCatalog.backgrounds.length,
              itemBuilder: (context, index) {
                final item = ItemCatalog.backgrounds[index];
                final isUnlocked = currentLevel >= item.unlockLevel;
                final isSelected = currentConfig.selectedBackground == item.id;

                return GestureDetector(
                  onTap: isUnlocked
                      ? () async {
                          Navigator.pop(context);
                          setState(() => _isLoading = true);

                          final newConfig = AvatarConfig(
                            gender: currentConfig.gender,
                            variant: currentConfig.variant,
                            selectedBackground: item.id,
                          );

                          final updatedUser = _user!.copyWith(
                            avatarConfig: Value(newConfig.toJson()),
                            isDirty: true,
                          );
                          _user = updatedUser;

                          await ref
                              .read(userRepositoryProvider)
                              .saveLocalUser(_user!);
                          setState(() => _isLoading = false);
                        }
                      : null,
                  child: Container(
                    width: 140,
                    margin: const EdgeInsets.only(right: 12, bottom: 16),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(12),
                      border: Border.all(
                        color:
                            isSelected ? AppTheme.primaryColor : Colors.white12,
                        width: isSelected ? 3 : 1,
                      ),
                      image: DecorationImage(
                        image: AssetImage(item.assetPath),
                        fit: BoxFit.cover,
                        colorFilter: isUnlocked
                            ? null
                            : const ColorFilter.mode(
                                Colors.black87, BlendMode.darken),
                      ),
                    ),
                    child: Stack(
                      children: [
                        if (!isUnlocked)
                          Center(
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                const Icon(Icons.lock, color: Colors.white54),
                                const SizedBox(height: 4),
                                Text(
                                  'Lvl ${item.unlockLevel}',
                                  style: const TextStyle(
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold,
                                      shadows: [
                                        Shadow(
                                            blurRadius: 4, color: Colors.black)
                                      ]),
                                ),
                              ],
                            ),
                          ),
                        if (isSelected)
                          const Positioned(
                            top: 8,
                            right: 8,
                            child: Icon(Icons.check_circle,
                                color: AppTheme.primaryColor),
                          ),
                        Positioned(
                          bottom: 0,
                          left: 0,
                          right: 0,
                          child: Container(
                            padding: const EdgeInsets.all(8),
                            decoration: BoxDecoration(
                              color: Colors.black.withValues(alpha: 0.7),
                              borderRadius: const BorderRadius.vertical(
                                  bottom: Radius.circular(10)),
                            ),
                            child: Text(
                              item.name,
                              style: const TextStyle(
                                  color: Colors.white,
                                  fontSize: 10,
                                  overflow: TextOverflow.ellipsis),
                              textAlign: TextAlign.center,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  void _confirmDangerAction(
      String title, String content, VoidCallback onConfirm) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(title, style: const TextStyle(color: AppTheme.errorColor)),
        content: Text(content),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('CANCEL'),
          ),
          ElevatedButton(
            style:
                ElevatedButton.styleFrom(backgroundColor: AppTheme.errorColor),
            onPressed: () {
              Navigator.pop(context);
              onConfirm();
            },
            child: const Text('CONFIRM'),
          ),
        ],
      ),
    );
  }

  void _showAvatarEditor() {
    final currentConfig = _user?.avatarConfig != null
        ? AvatarConfig.fromJson(_user!.avatarConfig!)
        : const AvatarConfig();

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      useSafeArea: true,
      backgroundColor: AppTheme.backgroundColor,
      builder: (context) => Scaffold(
        appBar: AppBar(
          title: const Text('Edit Appearance'),
          leading: IconButton(
            icon: const Icon(Icons.close),
            onPressed: () => Navigator.pop(context),
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.pop(context, _tempAvatarConfig);
              },
              child: const Text('SAVE',
                  style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: AppTheme.primaryColor)),
            ),
          ],
        ),
        body: AvatarEditor(
          initialConfig: currentConfig,
          onChanged: (conf) => _tempAvatarConfig = conf,
        ),
      ),
    ).then((result) async {
      if (result is AvatarConfig) {
        setState(() => _isLoading = true);

        final updatedUser = _user!.copyWith(
          avatarConfig: Value(result.toJson()),
          isDirty: true,
        );
        _user = updatedUser;

        await ref.read(userRepositoryProvider).saveLocalUser(_user!);
        setState(() => _isLoading = false);
      }
    });
  }

  AccessoryTemplate _getTemplateFromSettings(Map<String, dynamic> settings) {
    final key = settings['accessory_template'] as String?;
    if (key == 'hypertrophy') return AccessoryTemplate.hypertrophy;
    if (key == 'conditioning') return AccessoryTemplate.conditioning;
    if (key == 'journey_pullup') return AccessoryTemplate.journeyPullup;
    return AccessoryTemplate.none;
  }

  Future<void> _updateTemplate(AccessoryTemplate newTemplate) async {
    setState(() => _isLoading = true);

    String templateKey = 'none';
    if (newTemplate == AccessoryTemplate.hypertrophy) {
      templateKey = 'hypertrophy';
    }
    if (newTemplate == AccessoryTemplate.conditioning) {
      templateKey = 'conditioning';
    }
    if (newTemplate == AccessoryTemplate.journeyPullup) {
      templateKey = 'journey_pullup';
    }

    final currentSettings =
        Map<String, dynamic>.from(_user!.inventorySettings ?? {});
    currentSettings['accessory_template'] = templateKey;

    try {
      final updatedUser = _user!.copyWith(
        inventorySettings: Value(currentSettings),
        isDirty: true,
      );

      await ref.read(userRepositoryProvider).saveLocalUser(updatedUser);

      ref.read(userRepositoryProvider).updateInventory(currentSettings);

      setState(() {
        _user = updatedUser;
        _isLoading = false;
      });
    } catch (e) {
      setState(() => _isLoading = false);
      // Error handling...
    }
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    final userRepo = ref.watch(userRepositoryProvider);
    final avatarConfig = _user?.avatarConfig != null
        ? AvatarConfig.fromJson(_user!.avatarConfig!)
        : const AvatarConfig();

    return Scaffold(
      appBar: AppBar(
        title: const Text('Edit Profile'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => context.go('/hub'),
        ),
        actions: [
          if (_hasChanges)
            TextButton(
              onPressed: _isLoading ? null : _saveBodyweight,
              child: const Text('SAVE',
                  style: TextStyle(
                      color: AppTheme.primaryColor,
                      fontWeight: FontWeight.bold)),
            ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : SafeArea(
              child: ListView(
                padding: const EdgeInsets.all(16),
                children: [
                  Center(
                    child: Stack(
                      children: [
                        AvatarRenderer(
                          config: avatarConfig,
                          size: 120,
                        ),
                        Positioned(
                          bottom: 0,
                          right: 0,
                          child: CircleAvatar(
                            backgroundColor: AppTheme.surfaceColor,
                            radius: 18,
                            child: IconButton(
                              icon: const Icon(Icons.edit, size: 16),
                              onPressed: _showAvatarEditor,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 32),
                  Center(
                    child: OutlinedButton.icon(
                      onPressed: _showBackgroundSelector,
                      icon: const Icon(Icons.landscape),
                      label: const Text('CHANGE SCENERY'),
                    ),
                  ),
                  const SizedBox(height: 32),
                  Text('Physical Stats',
                      style: Theme.of(context)
                          .textTheme
                          .titleLarge
                          ?.copyWith(color: AppTheme.textPrimary)),
                  const SizedBox(height: 16),
                  Card(
                    child: Padding(
                      padding: const EdgeInsets.all(16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('Current Bodyweight',
                              style: Theme.of(context).textTheme.bodyMedium),
                          Row(
                            children: [
                              Expanded(
                                child: Slider(
                                  value: _currentBodyweight,
                                  min: 40,
                                  max: 150,
                                  divisions: 220,
                                  label: _currentBodyweight.toStringAsFixed(1),
                                  activeColor: AppTheme.primaryColor,
                                  onChanged: (val) => setState(() {
                                    _currentBodyweight = val;
                                    _hasChanges = true;
                                  }),
                                ),
                              ),
                              Text(
                                '${_currentBodyweight.toStringAsFixed(1)} kg',
                                style: Theme.of(context)
                                    .textTheme
                                    .titleMedium
                                    ?.copyWith(
                                      fontWeight: FontWeight.bold,
                                      color: AppTheme.primaryColor,
                                    ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                  const SizedBox(height: 32),
                  Text('Training Focus',
                      style: Theme.of(context)
                          .textTheme
                          .titleLarge
                          ?.copyWith(color: AppTheme.textPrimary)),
                  const SizedBox(height: 16),
                  Card(
                    child: Padding(
                      padding: const EdgeInsets.all(16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('Accessory Template',
                              style: Theme.of(context).textTheme.bodyMedium),
                          const SizedBox(height: 12),
                          _buildTemplateSelector(),
                        ],
                      ),
                    ),
                  ),
                  Text('Account Security',
                      style: Theme.of(context)
                          .textTheme
                          .titleLarge
                          ?.copyWith(color: AppTheme.textPrimary)),
                  const SizedBox(height: 8),
                  ListTile(
                    leading: const Icon(Icons.lock_outline),
                    title: const Text('Change Password'),
                    trailing: const Icon(Icons.chevron_right),
                    onTap: _showChangePasswordDialog,
                  ),
                  ListTile(
                    leading: const Icon(Icons.privacy_tip_outlined),
                    title: Text(l10n.privacyPolicyButton),
                    trailing: const Icon(Icons.arrow_forward_ios, size: 16),
                    onTap: () => context.push('/privacy-policy'),
                  ),
                  const Divider(),
                  const SizedBox(height: 24),
                  Text('Danger Zone',
                      style: Theme.of(context)
                          .textTheme
                          .titleLarge
                          ?.copyWith(color: AppTheme.errorColor)),
                  const SizedBox(height: 8),
                  Container(
                    decoration: BoxDecoration(
                      border: Border.all(
                          color: AppTheme.errorColor.withValues(alpha: 0.5)),
                      borderRadius: BorderRadius.circular(12),
                      color: AppTheme.errorColor.withValues(alpha: 0.05),
                    ),
                    child: Column(
                      children: [
                        ListTile(
                          leading: const Icon(Icons.refresh,
                              color: AppTheme.errorColor),
                          title: const Text('Reset Progress',
                              style: TextStyle(color: AppTheme.errorColor)),
                          subtitle: const Text(
                              'Resets Level, XP and Training History'),
                          onTap: () => _confirmDangerAction(
                            'Reset Progress?',
                            'This will delete all your workouts and reset your Level to 1. This cannot be undone.',
                            () async {
                              setState(() => _isLoading = true);
                              await userRepo.resetProgress();
                              if (mounted) {
                                setState(() => _isLoading = false);
                                context.go('/hub');
                              }
                            },
                          ),
                        ),
                        const Divider(height: 1),
                        ListTile(
                          leading: const Icon(Icons.delete_forever,
                              color: AppTheme.errorColor),
                          title: const Text('Delete Account',
                              style: TextStyle(color: AppTheme.errorColor)),
                          subtitle: const Text(
                              'Permanently delete your account and data'),
                          onTap: () => _confirmDangerAction(
                            'Delete Account?',
                            'Are you sure you want to delete your account? All data will be lost forever.',
                            () async {
                              setState(() => _isLoading = true);
                              try {
                                await userRepo.deleteAccount();
                                if (mounted) context.go('/login');
                              } catch (e) {
                                if (mounted) {
                                  setState(() => _isLoading = false);
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    SnackBar(content: Text('Error: $e')),
                                  );
                                }
                              }
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 32),
                  OutlinedButton.icon(
                    onPressed: () async {
                      await userRepo.logout();
                      if (mounted) context.go('/login');
                    },
                    icon: const Icon(Icons.logout),
                    label: const Text('LOGOUT'),
                    style: OutlinedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(vertical: 16),
                    ),
                  ),
                  const SizedBox(
                    height: 50,
                  )
                ],
              ),
            ),
    );
  }

  Widget _buildTemplateSelector() {
    final current = _getTemplateFromSettings(_user?.inventorySettings ?? {});

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _RadioTile<AccessoryTemplate>(
          value: AccessoryTemplate.none,
          groupValue: current,
          title: 'Strength Only',
          subtitle: 'Main Lifts + FSL. Pure & Fast.',
          onChanged: (val) => _updateTemplate(val!),
        ),
        const Divider(height: 1),
        _RadioTile<AccessoryTemplate>(
          value: AccessoryTemplate.hypertrophy,
          groupValue: current,
          title: 'Hypertrophy Support',
          subtitle: 'Bodybuilding accessories to build muscle armor.',
          onChanged: (val) => _updateTemplate(val!),
        ),
        const Divider(height: 1),
        _RadioTile<AccessoryTemplate>(
          value: AccessoryTemplate.conditioning,
          groupValue: current,
          title: 'The Engine (Conditioning)',
          subtitle: '15 min Kettlebell intervals to boost stamina.',
          onChanged: (val) => _updateTemplate(val!),
        ),
        const Padding(
          padding: EdgeInsets.fromLTRB(16, 24, 16, 8),
          child: Text(
            'ACTIVE JOURNEYS',
            style: TextStyle(
                color: Colors.grey,
                fontSize: 12,
                fontWeight: FontWeight.bold,
                letterSpacing: 1.5),
          ),
        ),
        _RadioTile<AccessoryTemplate>(
          value: AccessoryTemplate.journeyPullup,
          groupValue: current,
          title: 'Quest: The First Pull-Up',
          subtitle: 'Specific progression to master your bodyweight.',
          onChanged: (val) => _updateTemplate(val!),
        ),
      ],
    );
  }
}

class _RadioTile<T> extends StatelessWidget {
  final T value;
  final T groupValue;
  final String title;
  final String subtitle;
  final ValueChanged<T?> onChanged;

  const _RadioTile({
    required this.value,
    required this.groupValue,
    required this.title,
    required this.subtitle,
    required this.onChanged,
  });

  @override
  Widget build(BuildContext context) {
    final isSelected = value == groupValue;
    return RadioListTile<T>(
      value: value,
      groupValue: groupValue,
      onChanged: onChanged,
      activeColor: AppTheme.primaryColor,
      title: Text(
        title,
        style: TextStyle(
          fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
          color: isSelected ? AppTheme.primaryColor : Colors.white,
        ),
      ),
      subtitle: Text(subtitle, style: const TextStyle(fontSize: 12)),
      contentPadding: EdgeInsets.zero,
    );
  }
}
