import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/constants/app_constants.dart';
import '../../core/theme/app_theme.dart';
import '../../data/models/weapon.dart';
import '../../data/repositories/session_repository.dart';
import 'weapon_detail_screen.dart';

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

  @override
  State<WeaponListScreen> createState() => _WeaponListScreenState();
}

class _WeaponListScreenState extends State<WeaponListScreen> {
  List<Weapon> _weapons = [];
  bool _isLoading = true;

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

  Future<void> _loadWeapons() async {
    final repository = context.read<SessionRepository>();
    final weapons = await repository.getWeapons();
    if (mounted) {
      setState(() {
        _weapons = weapons;
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Mon Armurerie'),
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _weapons.isEmpty
              ? _buildEmptyState()
              : _buildWeaponList(),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _showAddWeaponDialog(context),
        child: const Icon(Icons.add),
      ),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.shield, size: 64, color: Colors.grey[400]),
          const SizedBox(height: 16),
          const Text('Aucune arme enregistrée'),
          const SizedBox(height: 24),
          ElevatedButton(
            onPressed: () => _showAddWeaponDialog(context),
            child: const Text('Ajouter ma première arme'),
          ),
        ],
      ),
    );
  }

  Widget _buildWeaponList() {
    return ListView.builder(
      padding: const EdgeInsets.all(AppConstants.defaultPadding),
      itemCount: _weapons.length,
      itemBuilder: (context, index) {
        final weapon = _weapons[index];
        return Card(
          margin: const EdgeInsets.only(bottom: 12),
          child: ListTile(
            leading: CircleAvatar(
              backgroundColor: AppTheme.primaryColor.withValues(alpha: 0.1),
              child: Icon(
                weapon.type == WeaponType.handgun ? Icons.shield : Icons.ads_click,
                color: AppTheme.primaryColor,
              ),
            ),
            title: Text(weapon.displayName, style: const TextStyle(fontWeight: FontWeight.bold)),
            subtitle: Text('${weapon.type.displayName} • ${weapon.caliber}'),
            trailing: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Text('${weapon.magazineCount} chargeurs', style: const TextStyle(fontSize: 12)),
                Text('${weapon.magazineCapacity} coups', style: const TextStyle(fontSize: 12, color: Colors.grey)),
              ],
            ),
            onTap: () async {
              await Navigator.push(
                context,
                MaterialPageRoute(builder: (_) => WeaponDetailScreen(weapon: weapon)),
              );
              _loadWeapons(); // Reload in case it was edited or maintenance was added
            },
            onLongPress: () => _confirmDelete(context, weapon),
          ),
        );
      },
    );
  }

  void _showAddWeaponDialog(BuildContext context) async {
    final nameController = TextEditingController();
    final caliberController = TextEditingController();
    final magCountController = TextEditingController(text: '2');
    final magCapController = TextEditingController(text: '15');
    WeaponType selectedType = WeaponType.handgun;

    final result = await showDialog<bool>(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setState) => AlertDialog(
          title: const Text('Ajouter une arme'),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                TextField(
                  controller: nameController,
                  decoration: const InputDecoration(labelText: 'Nom de l\'arme', hintText: 'ex: Glock 17'),
                ),
                DropdownButtonFormField<WeaponType>(
                  value: selectedType,
                  decoration: const InputDecoration(labelText: 'Type'),
                  items: WeaponType.values.map((t) => DropdownMenuItem(value: t, child: Text(t.displayName))).toList(),
                  onChanged: (v) => setState(() => selectedType = v!),
                ),
                TextField(
                  controller: caliberController,
                  decoration: const InputDecoration(labelText: 'Calibre', hintText: 'ex: 9mm, .22LR'),
                ),
                Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: magCountController,
                        decoration: const InputDecoration(labelText: 'Chargeurs'),
                        keyboardType: TextInputType.number,
                      ),
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: TextField(
                        controller: magCapController,
                        decoration: const InputDecoration(labelText: 'Capacité'),
                        keyboardType: TextInputType.number,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          actions: [
            TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Annuler')),
            ElevatedButton(onPressed: () => Navigator.pop(context, true), child: const Text('Ajouter')),
          ],
        ),
      ),
    );

    if (result == true && nameController.text.isNotEmpty) {
      final repository = context.read<SessionRepository>();
      await repository.addWeapon(
        name: nameController.text,
        type: selectedType,
        caliber: caliberController.text,
        magazineCount: int.tryParse(magCountController.text) ?? 1,
        magazineCapacity: int.tryParse(magCapController.text) ?? 10,
      );
      _loadWeapons();
    }
  }

  void _confirmDelete(BuildContext context, Weapon weapon) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Supprimer'),
        content: Text('Voulez-vous supprimer ${weapon.name} de votre armurerie ?'),
        actions: [
          TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Annuler')),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('Supprimer', style: TextStyle(color: AppTheme.errorColor)),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      final repository = context.read<SessionRepository>();
      await repository.deleteWeapon(weapon.id);
      _loadWeapons();
    }
  }
}
