import 'dart:developer';

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 '../../../../core/constants/app_constants.dart';
import '../../../../shared/data/repositories/user_repository.dart';
import '../../../authentication/data/repositories/auth_repository.dart';
import '../../../../shared/data/repositories/cycle_repository.dart';
import '../../../inventory/presentation/widgets/plate_counter.dart';
import 'bodyweight_input_screen.dart';

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

  @override
  ConsumerState<InventorySetupScreen> createState() =>
      _InventorySetupScreenState();
}

class _InventorySetupScreenState extends ConsumerState<InventorySetupScreen> {
  double _barWeight = AppConstants.defaultBarWeight;
  Map<double, int> _plateInventory = {
    25.0: 2,
    20.0: 2,
    15.0: 0,
    10.0: 2,
    5.0: 2,
    2.5: 2,
    1.25: 2,
  };

  final Map<String, bool> _bandInventory = {
    'Blue': true,
    'Green': true,
    'Orange': false,
    'Red': false,
  };

  bool _isLoading = false;

  void _applyPreset(String preset) {
    setState(() {
      switch (preset) {
        case 'home':
          _plateInventory = {
            25.0: 0,
            20.0: 2,
            15.0: 0,
            10.0: 2,
            5.0: 2,
            2.5: 2,
            1.25: 2,
          };
          break;
        case 'commercial':
          _plateInventory = {
            25.0: 4,
            20.0: 4,
            15.0: 2,
            10.0: 4,
            5.0: 4,
            2.5: 4,
            1.25: 2,
          };
          break;
        case 'minimal':
          _plateInventory = {
            25.0: 0,
            20.0: 2,
            15.0: 0,
            10.0: 0,
            5.0: 2,
            2.5: 0,
            1.25: 0,
          };
          break;
      }
    });
  }

  void _handleNext() {
    final platesList = <double>[];
    _plateInventory.forEach((weight, count) {
      for (int i = 0; i < count; i++) {
        platesList.add(weight);
      }
    });

    final bandsList = <Map<String, dynamic>>[];
    _bandInventory.forEach((color, isSelected) {
      if (isSelected) {
        bandsList.add({
          'color': color,
          'resistance_kg': AppConstants.defaultBands[color] ?? 0.0,
          'count': 1,
        });
      }
    });

    final inventorySettings = {
      'bar_weight': _barWeight,
      'plates': platesList,
      'bands': bandsList,
    };

    ref.read(onboardingDataProvider.notifier).updateData({
      'inventory_settings': inventorySettings,
    });

    context.push('/onboarding/avatar');
  }

  Future<void> _handleFinish() async {
    setState(() => _isLoading = true);

    try {
      final onboardingData = ref.read(onboardingDataProvider);
      final authRepo = ref.read(authRepositoryProvider);

      final platesList = <double>[];
      _plateInventory.forEach((weight, count) {
        for (int i = 0; i < count; i++) {
          platesList.add(weight);
        }
      });

      final bandsList = <Map<String, dynamic>>[];
      _bandInventory.forEach((color, isSelected) {
        if (isSelected) {
          bandsList.add({
            'color': color,
            'resistance_kg': AppConstants.defaultBands[color] ?? 0.0,
            'count': 1,
          });
        }
      });

      final inventorySettings = {
        'bar_weight': _barWeight,
        'plates': platesList,
        'bands': bandsList,
      };

      final user = await authRepo.register(
        email: onboardingData['email'] ?? '',
        username: onboardingData['username'] ?? '',
        password: onboardingData['password'] ?? '',
        bodyweight: onboardingData['bodyweight'] ?? 80.0,
        inventorySettings: inventorySettings,
      );

      log('✅ User registered: ${user.serverId}');

      final trainingMaxes =
          onboardingData['training_maxes'] as Map<String, dynamic>?;

      if (trainingMaxes != null) {
        final cycleRepo = ref.read(cycleRepositoryProvider);
        final tmMap = <String, double>{
          'squat': (trainingMaxes['squat'] as num?)?.toDouble() ?? 100.0,
          'pullup': (trainingMaxes['pullup'] as num?)?.toDouble() ?? 80.0,
          'dip': (trainingMaxes['dip'] as num?)?.toDouble() ?? 90.0,
        };

        log('📊 Creating cycle with TMs: $tmMap');
        await cycleRepo.createCycle(tmMap);
        log('✅ Cycle created successfully');
      }

      if (mounted) {
        ref.read(onboardingDataProvider.notifier).clear();
        context.go('/hub');
      }
    } catch (e, stackTrace) {
      log('❌ Setup failed: $e');
      log('Stack trace: $stackTrace');

      if (mounted) {
        final l10n = AppLocalizations.of(context)!;
        String message = l10n.setupFailed(e.toString());
        if (e.toString().toLowerCase().contains('unique') ||
            e.toString().toLowerCase().contains('email')) {
          message = l10n.setupEmailExists;
        }

        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(message),
            backgroundColor: AppTheme.errorColor,
            duration: const Duration(seconds: 5),
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  Color _getBandColor(String name) {
    switch (name) {
      case 'Blue':
        return Colors.blue;
      case 'Green':
        return Colors.green;
      case 'Orange':
        return Colors.orange;
      case 'Red':
        return Colors.red;
      default:
        return Colors.grey;
    }
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.setupEquipmentTitle),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => context.go('/onboarding/strength-test'),
        ),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(24),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              LinearProgressIndicator(
                value: 0.75,
                backgroundColor: AppTheme.xpBarBackground,
                color: AppTheme.primaryColor,
              ),
              const SizedBox(height: 32),
              Text(
                l10n.setupInventoryTitle,
                style: Theme.of(context).textTheme.displayMedium,
              ),
              const SizedBox(height: 8),
              Text(
                l10n.setupInventorySubtitle,
                style: Theme.of(context).textTheme.bodyMedium,
              ),
              const SizedBox(height: 32),
              Text(
                l10n.inventoryBarbellWeight,
                style: Theme.of(context)
                    .textTheme
                    .titleLarge
                    ?.copyWith(color: AppTheme.textPrimary),
              ),
              const SizedBox(height: 12),
              Slider(
                value: _barWeight,
                min: 10,
                max: 25,
                divisions: 3,
                label: '${_barWeight.toStringAsFixed(0)} ${l10n.unitKg}',
                activeColor: AppTheme.primaryColor,
                onChanged: (value) {
                  setState(() => _barWeight = value);
                },
              ),
              Text(
                '${_barWeight.toStringAsFixed(0)} ${l10n.unitKg}',
                style: Theme.of(context).textTheme.headlineMedium?.copyWith(
                      color: AppTheme.primaryColor,
                    ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 32),
              Text(
                l10n.inventoryPresets,
                style: Theme.of(context)
                    .textTheme
                    .titleLarge
                    ?.copyWith(color: AppTheme.textPrimary),
              ),
              const SizedBox(height: 12),
              LayoutBuilder(
                builder: (context, constraints) {
                  final screenWidth = constraints.maxWidth;
                  final chipWidth = 130.0;
                  final spacing = 8.0;
                  final totalWidth = (chipWidth * 3) + (spacing * 2);

                  if (screenWidth < totalWidth) {
                    return Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        _buildPresetButton(l10n.inventoryPresetHome, 'home'),
                        const SizedBox(height: 8),
                        _buildPresetButton(
                            l10n.inventoryPresetCommercial, 'commercial'),
                        const SizedBox(height: 8),
                        _buildPresetButton(
                            l10n.inventoryPresetMinimal, 'minimal'),
                      ],
                    );
                  } else {
                    return Row(
                      children: [
                        Expanded(
                            child: _buildPresetButton(
                                l10n.inventoryPresetHome, 'home')),
                        const SizedBox(width: 8),
                        Expanded(
                            child: _buildPresetButton(
                                l10n.inventoryPresetCommercial, 'commercial')),
                        const SizedBox(width: 8),
                        Expanded(
                            child: _buildPresetButton(
                                l10n.inventoryPresetMinimal, 'minimal')),
                      ],
                    );
                  }
                },
              ),
              const SizedBox(height: 32),
              Text(
                l10n.inventoryPlates,
                style: Theme.of(context)
                    .textTheme
                    .titleLarge
                    ?.copyWith(color: AppTheme.textPrimary),
              ),
              const SizedBox(height: 12),
              ..._plateInventory.entries.map((entry) {
                return PlateCounter(
                  weight: entry.key,
                  count: entry.value,
                  onChanged: (newCount) {
                    setState(() {
                      _plateInventory[entry.key] = newCount;
                    });
                  },
                );
              }).toList(),
              const SizedBox(height: 32),
              Text(
                l10n.inventoryBands,
                style: Theme.of(context)
                    .textTheme
                    .titleLarge
                    ?.copyWith(color: AppTheme.textPrimary),
              ),
              const SizedBox(height: 8),
              Text(
                l10n.setupBandsSubtitle,
                style: Theme.of(context)
                    .textTheme
                    .bodySmall
                    ?.copyWith(color: AppTheme.textSecondary),
              ),
              const SizedBox(height: 12),
              LayoutBuilder(
                builder: (context, constraints) {
                  final screenWidth = constraints.maxWidth;

                  int crossAxisCount = 2;
                  if (screenWidth > 600) {
                    crossAxisCount = 4;
                  } else if (screenWidth > 400) {
                    crossAxisCount = 2;
                  }

                  final bandEntries = _bandInventory.entries.toList();

                  return GridView.builder(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: crossAxisCount,
                      crossAxisSpacing: 8,
                      mainAxisSpacing: 8,
                      childAspectRatio: 2.5,
                    ),
                    itemCount: bandEntries.length,
                    itemBuilder: (context, index) {
                      final entry = bandEntries[index];
                      final resistance =
                          AppConstants.defaultBands[entry.key] ?? 0;

                      return _buildBandChip(
                        entry.key,
                        resistance.toInt(),
                        entry.value,
                      );
                    },
                  );
                },
              ),
              const SizedBox(height: 32),
              ElevatedButton(
                onPressed: _isLoading ? null : _handleNext,
                child: _isLoading
                    ? const SizedBox(
                        height: 20,
                        width: 20,
                        child: CircularProgressIndicator(
                          color: Colors.black,
                          strokeWidth: 2,
                        ),
                      )
                    : Text(l10n.nextStepButton),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildPresetButton(String label, String preset) {
    return OutlinedButton(
      onPressed: () => _applyPreset(preset),
      style: OutlinedButton.styleFrom(
        padding: const EdgeInsets.symmetric(vertical: 12),
      ),
      child: Text(label),
    );
  }

  Widget _buildBandChip(String color, int resistance, bool isSelected) {
    return InkWell(
      onTap: () {
        setState(() {
          _bandInventory[color] = !isSelected;
        });
      },
      borderRadius: BorderRadius.circular(8),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        decoration: BoxDecoration(
          color: isSelected
              ? _getBandColor(color).withValues(alpha: 0.2)
              : AppTheme.surfaceColor,
          border: Border.all(
            color: _getBandColor(color),
            width: isSelected ? 2 : 1,
          ),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            if (isSelected)
              Icon(
                Icons.check_circle,
                color: _getBandColor(color),
                size: 18,
              ),
            if (isSelected) const SizedBox(width: 4),
            Expanded(
              child: Text(
                '$color (~$resistance${AppLocalizations.of(context)!.unitKg})',
                style: TextStyle(
                  color: isSelected ? Colors.white : AppTheme.textSecondary,
                  fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                  fontSize: 12,
                ),
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
