import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';

import '../../../core/api/api_error_mapper.dart';
import '../../auth/data/auth_providers.dart';
import '../data/inventory_providers.dart';

class ConsumeInventoryScreen extends ConsumerStatefulWidget {
  final int itemId;

  const ConsumeInventoryScreen({super.key, required this.itemId});

  @override
  ConsumerState<ConsumeInventoryScreen> createState() =>
      _ConsumeInventoryScreenState();
}

class _ConsumeInventoryScreenState
    extends ConsumerState<ConsumeInventoryScreen> {
  final _formKey = GlobalKey<FormState>();
  final _amountController = TextEditingController();
  final _commentController = TextEditingController();
  bool _saving = false;

  @override
  void dispose() {
    _amountController.dispose();
    _commentController.dispose();
    super.dispose();
  }

  Future<void> _save() async {
    if (!_formKey.currentState!.validate()) return;
    setState(() => _saving = true);
    try {
      final token = await ref.read(authStateProvider.future);
      final amount = double.parse(
          _amountController.text.trim().replaceAll(',', '.'));
      await ref.read(inventoryRepositoryProvider).consumeInventoryItem(
            widget.itemId,
            amountUsed: amount,
            comment: _commentController.text.trim().isEmpty
                ? null
                : _commentController.text.trim(),
            token: token,
          );
      ref.invalidate(inventoryDetailProvider(widget.itemId));
      ref.invalidate(inventoryProvider);
      if (mounted) context.go('/inventory');
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text(mapErrorToUserMessage(e, context))));
      }
    } finally {
      if (mounted) setState(() => _saving = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final itemAsync = ref.watch(inventoryDetailProvider(widget.itemId));

    return Scaffold(
      appBar: AppBar(
        title: itemAsync.maybeWhen(
          data: (item) => Text('Konsumera: ${item.productName}'),
          orElse: () => const Text('Konsumera'),
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              if (itemAsync.hasValue) ...[
                Text(
                  'Tillgängligt: ${itemAsync.value!.quantity} ${itemAsync.value!.unit}',
                  style: Theme.of(context).textTheme.bodyMedium,
                ),
                const SizedBox(height: 16),
              ],
              TextFormField(
                controller: _amountController,
                decoration: InputDecoration(
                  labelText: 'Mängd att konsumera *',
                  border: const OutlineInputBorder(),
                  suffixText: itemAsync.maybeWhen(
                    data: (item) => item.unit,
                    orElse: () => null,
                  ),
                ),
                keyboardType:
                    const TextInputType.numberWithOptions(decimal: true),
                autofocus: true,
                enabled: !_saving,
                validator: (v) {
                  if (v == null || v.trim().isEmpty) return 'Ange mängd';
                  final parsed =
                      double.tryParse(v.trim().replaceAll(',', '.'));
                  if (parsed == null || parsed <= 0) {
                    return 'Ange ett positivt tal';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 12),
              TextFormField(
                controller: _commentController,
                decoration: const InputDecoration(
                  labelText: 'Kommentar (valfri)',
                  border: OutlineInputBorder(),
                ),
                enabled: !_saving,
              ),
              const SizedBox(height: 24),
              FilledButton(
                onPressed: _saving ? null : _save,
                child: _saving
                    ? const SizedBox(
                        height: 20,
                        width: 20,
                        child: CircularProgressIndicator(
                            strokeWidth: 2, color: Colors.white),
                      )
                    : const Text('Konsumera'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
