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 '../../../core/l10n/l10n.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(context.l10n.inventoryConsumeNameTitle(item.productName)),
          orElse: () => Text(context.l10n.inventoryConsumeAction),
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              if (itemAsync.hasValue) ...[
                Text(
                  context.l10n.inventoryAvailableLabel(
                    itemAsync.value!.quantity.toString(),
                    itemAsync.value!.unit,
                  ),
                  style: Theme.of(context).textTheme.bodyMedium,
                ),
                const SizedBox(height: 16),
              ],
              TextFormField(
                controller: _amountController,
                decoration: InputDecoration(
                  labelText: context.l10n.inventoryConsumeAmountLabel,
                  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 context.l10n.quantityHint;
                  final parsed =
                      double.tryParse(v.trim().replaceAll(',', '.'));
                  if (parsed == null || parsed <= 0) {
                    return context.l10n.enterPositiveNumber;
                  }
                  return null;
                },
              ),
              const SizedBox(height: 12),
              TextFormField(
                controller: _commentController,
                decoration: InputDecoration(
                  labelText: context.l10n.commentOptionalLabel,
                  border: const 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),
                      )
                      : Text(context.l10n.inventoryConsumeAction),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
