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 '../widgets/plate_counter.dart';

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

  @override
  ConsumerState<InventoryScreen> createState() => _InventoryScreenState();
}

class _InventoryScreenState extends ConsumerState<InventoryScreen> {
  double _barWeight = 20.0;
  Map<double, int> _plateInventory = {};
  Map<String, bool> _bandInventory = {};
  bool _isLoading = true;
  bool _hasChanges = false;

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

  Future<void> _loadCurrentInventory() async {
    final userRepo = ref.read(userRepositoryProvider);
    final inventory = await userRepo.getInventorySettingsAsync();

    final barWeight = (inventory['bar_weight'] as num?)?.toDouble() ?? 20.0;

    final platesList = (inventory['plates'] as List?)
            ?.map((e) => (e as num).toDouble())
            .toList() ??
        [];
    final plateMap = <double, int>{
      25.0: 0,
      20.0: 0,
      15.0: 0,
      10.0: 0,
      5.0: 0,
      2.5: 0,
      1.25: 0
    };

    for (var p in platesList) {
      if (plateMap.containsKey(p)) {
        plateMap[p] = (plateMap[p] ?? 0) + 1;
      }
    }

    final bandsList = (inventory['bands'] as List?) ?? [];
    final bandMap = <String, bool>{
      'Blue': false,
      'Green': false,
      'Orange': false,
      'Red': false
    };

    for (var b in bandsList) {
      final band = b as Map<String, dynamic>;
      final color = band['color'] as String;
      if (bandMap.containsKey(color)) {
        bandMap[color] = true;
      }
    }

    if (mounted) {
      setState(() {
        _barWeight = barWeight;
        _plateInventory = plateMap;
        _bandInventory = bandMap;
        _isLoading = false;
      });
    }
  }

  void _applyPreset(String preset) {
    setState(() {
      _hasChanges = true;
      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;
      }
    });
  }

  Future<void> _saveChanges() async {
    final l10n = AppLocalizations.of(context)!;
    setState(() => _isLoading = true);
    try {
      final userRepo = ref.read(userRepositoryProvider);

      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 newSettings = {
        'bar_weight': _barWeight,
        'plates': platesList,
        'bands': bandsList,
      };

      await userRepo.updateInventory(newSettings);

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(l10n.inventoryUpdatedSuccess)),
        );
        setState(() {
          _hasChanges = false;
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isLoading = false);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
              content: Text('Error saving: $e'),
              backgroundColor: AppTheme.errorColor),
        );
      }
    }
  }

  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)!;
    if (_isLoading && !_hasChanges) {
      return const Scaffold(body: Center(child: CircularProgressIndicator()));
    }

    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.inventoryTitle),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => context.go('/hub'),
        ),
        actions: [
          if (_hasChanges)
            TextButton(
              onPressed: _saveChanges,
              child: Text(l10n.saveButton,
                  style: TextStyle(
                      color: AppTheme.primaryColor,
                      fontWeight: FontWeight.bold)),
            )
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(l10n.inventoryBarbellWeight,
                        style: Theme.of(context).textTheme.titleMedium),
                    const SizedBox(height: 16),
                    Row(
                      children: [
                        const Icon(Icons.fitness_center,
                            size: 32, color: AppTheme.primaryColor),
                        Expanded(
                          child: Slider(
                            value: _barWeight,
                            min: 10,
                            max: 25,
                            divisions: 6,
                            label: '$_barWeight kg',
                            activeColor: AppTheme.primaryColor,
                            onChanged: (val) => setState(() {
                              _barWeight = val;
                              _hasChanges = true;
                            }),
                          ),
                        ),
                        Text('${_barWeight.toStringAsFixed(1)} kg',
                            style:
                                const TextStyle(fontWeight: FontWeight.bold)),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 24),
            Text(l10n.inventoryPresets,
                style: Theme.of(context)
                    .textTheme
                    .titleMedium
                    ?.copyWith(color: AppTheme.textSecondary)),
            const SizedBox(height: 8),
            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: [
                      _buildPresetChip(l10n.inventoryPresetHome, 'home'),
                      const SizedBox(height: 8),
                      _buildPresetChip(
                          l10n.inventoryPresetCommercial, 'commercial'),
                      const SizedBox(height: 8),
                      _buildPresetChip(l10n.inventoryPresetMinimal, 'minimal'),
                    ],
                  );
                } else {
                  return Row(
                    children: [
                      Expanded(
                          child: _buildPresetChip(
                              l10n.inventoryPresetHome, 'home')),
                      const SizedBox(width: 8),
                      Expanded(
                          child: _buildPresetChip(
                              l10n.inventoryPresetCommercial, 'commercial')),
                      const SizedBox(width: 8),
                      Expanded(
                          child: _buildPresetChip(
                              l10n.inventoryPresetMinimal, 'minimal')),
                    ],
                  );
                }
              },
            ),
            const SizedBox(height: 24),
            Text(l10n.inventoryPlates,
                style: Theme.of(context)
                    .textTheme
                    .titleMedium
                    ?.copyWith(color: AppTheme.textSecondary)),
            const SizedBox(height: 8),
            ..._plateInventory.entries.map((entry) {
              return PlateCounter(
                weight: entry.key,
                count: entry.value,
                onChanged: (newCount) {
                  setState(() {
                    _plateInventory[entry.key] = newCount;
                    _hasChanges = true;
                  });
                },
              );
            }),
            const SizedBox(height: 24),
            Text(l10n.inventoryBands,
                style: Theme.of(context)
                    .textTheme
                    .titleMedium
                    ?.copyWith(color: AppTheme.textSecondary)),
            const SizedBox(height: 8),
            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: 40),
            if (_hasChanges)
              ElevatedButton(
                onPressed: _isLoading ? null : _saveChanges,
                child: _isLoading
                    ? const SizedBox(
                        height: 20,
                        width: 20,
                        child: CircularProgressIndicator(
                          color: Colors.black,
                          strokeWidth: 2,
                        ),
                      )
                    : Text(l10n.saveChangesButton),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildPresetChip(String label, String preset) {
    return OutlinedButton(
      onPressed: () => _applyPreset(preset),
      style: OutlinedButton.styleFrom(
        padding: const EdgeInsets.symmetric(vertical: 12),
        side: BorderSide(
          color: AppTheme.primaryColor.withValues(alpha: 0.5),
        ),
      ),
      child: Text(label),
    );
  }

  Widget _buildBandChip(String color, int resistance, bool isSelected) {
    return InkWell(
      onTap: () {
        setState(() {
          _bandInventory[color] = !isSelected;
          _hasChanges = true;
        });
      },
      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}kg)',
                style: TextStyle(
                  color: isSelected
                      ? _getBandColor(color)
                      : AppTheme.textSecondary,
                  fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                  fontSize: 12,
                ),
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
