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/forms/form_options.dart';
import '../../../core/l10n/l10n.dart';
import '../../../core/ui/async_state_views.dart';
import '../../auth/data/auth_providers.dart';
import '../data/inventory_providers.dart';
import '../domain/inventory_item.dart';

class InventoryEditScreen extends ConsumerStatefulWidget {
  final int itemId;

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

  @override
  ConsumerState<InventoryEditScreen> createState() =>
      _InventoryEditScreenState();
}

class _InventoryEditScreenState extends ConsumerState<InventoryEditScreen> {
  final _formKey = GlobalKey<FormState>();
  final _quantityController = TextEditingController();
  final _unitController = TextEditingController();
  final _locationController = TextEditingController();
  final _brandController = TextEditingController();
  final _commentController = TextEditingController();

  bool _initialized = false;
  bool _opened = false;
  DateTime? _purchaseDate;
  DateTime? _bestBeforeDate;
  bool _saving = false;

  @override
  void dispose() {
    _quantityController.dispose();
    _unitController.dispose();
    _locationController.dispose();
    _brandController.dispose();
    _commentController.dispose();
    super.dispose();
  }

  void _initControllers(InventoryItem item) {
    _initialized = true;
    _quantityController.text = item.quantity.toString();
    _unitController.text = item.unit;
    _locationController.text = item.location ?? '';
    _brandController.text = item.brand ?? '';
    _commentController.text = item.comment ?? '';
    _opened = item.opened;
    _purchaseDate =
        item.purchaseDate != null ? DateTime.tryParse(item.purchaseDate!) : null;
    _bestBeforeDate = item.bestBeforeDate != null
        ? DateTime.tryParse(item.bestBeforeDate!)
        : null;
  }

  Future<void> _pickDate(bool isBestBefore) async {
    final picked = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(2000),
      lastDate: DateTime(2100),
    );
    if (picked != null) {
      setState(() {
        if (isBestBefore) {
          _bestBeforeDate = picked;
        } else {
          _purchaseDate = picked;
        }
      });
    }
  }

  Future<void> _save() async {
    if (!_formKey.currentState!.validate()) return;
    setState(() => _saving = true);
    try {
      final token = await ref.read(authStateProvider.future);
      final body = <String, dynamic>{
        'quantity':
            double.parse(_quantityController.text.trim().replaceAll(',', '.')),
        'unit': _unitController.text.trim(),
        'location': _locationController.text.trim().isEmpty
            ? null
            : _locationController.text.trim(),
        'brand': _brandController.text.trim().isEmpty
            ? null
            : _brandController.text.trim(),
        if (_purchaseDate != null)
          'purchaseDate': _purchaseDate!.toIso8601String(),
        if (_bestBeforeDate != null)
          'bestBeforeDate': _bestBeforeDate!.toIso8601String(),
        'opened': _opened,
        'comment': _commentController.text.trim().isEmpty
            ? null
            : _commentController.text.trim(),
      };
      await ref
          .read(inventoryRepositoryProvider)
          .updateInventoryItem(widget.itemId, body, token: token);
      ref.invalidate(inventoryDetailProvider(widget.itemId));
      ref.invalidate(inventoryProvider);
      if (mounted) context.pop();
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text(mapErrorToUserMessage(e, context))));
      }
    } finally {
      if (mounted) setState(() => _saving = false);
    }
  }

  String _formatDate(DateTime? dt) {
    if (dt == null) return context.l10n.selectDateLabel;
    return '${dt.year}-${dt.month.toString().padLeft(2, '0')}-${dt.day.toString().padLeft(2, '0')}';
  }

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

    return Scaffold(
      appBar: AppBar(title: Text(context.l10n.inventoryEditTitle)),
      body: itemAsync.when(
        loading: () => LoadingStateView(label: context.l10n.loadingLabel),
        error: (e, _) => ErrorStateView(
          message: mapErrorToUserMessage(e, context),
          onRetry: () => ref.invalidate(inventoryDetailProvider(widget.itemId)),
        ),
        data: (item) {
          if (!_initialized) _initControllers(item);
          return Form(
            key: _formKey,
            child: ListView(
              padding: const EdgeInsets.all(16),
              children: [
                Text(
                  item.productName,
                  style: Theme.of(context).textTheme.titleMedium,
                ),
                const SizedBox(height: 16),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                      flex: 2,
                      child: TextFormField(
                        controller: _quantityController,
                        decoration: const InputDecoration(
                          labelText: 'Mängd *',
                          border: OutlineInputBorder(),
                        ),
                        keyboardType: const TextInputType.numberWithOptions(
                            decimal: true),
                        enabled: !_saving,
                        validator: (v) {
                          if (v == null || v.trim().isEmpty) {
                            return 'Ange mängd';
                          }
                          if (double.tryParse(
                                  v.trim().replaceAll(',', '.')) ==
                              null) {
                            return 'Ogiltigt tal';
                          }
                          return null;
                        },
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: DropdownButtonFormField<String>(
                        initialValue: _unitController.text.trim().isEmpty
                            ? null
                            : _unitController.text.trim(),
                        isExpanded: true,
                        decoration: InputDecoration(
                          labelText: context.l10n.unitLabel,
                          border: const OutlineInputBorder(),
                        ),
                        items: unitOptions
                            .map(
                              (option) => DropdownMenuItem<String>(
                                value: option.value,
                                child: Text(option.label, overflow: TextOverflow.ellipsis),
                              ),
                            )
                            .toList(),
                        onChanged: _saving
                            ? null
                            : (value) =>
                                setState(() => _unitController.text = value ?? ''),
                        validator: (v) => (v == null || v.trim().isEmpty)
                            ? context.l10n.quantityHint
                            : null,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 12),
                DropdownButtonFormField<String>(
                  initialValue: _locationController.text.trim().isEmpty
                      ? null
                      : _locationController.text.trim(),
                  isExpanded: true,
                  decoration: InputDecoration(
                    labelText: context.l10n.locationLabel,
                    border: const OutlineInputBorder(),
                  ),
                  items: inventoryLocationOptions
                      .map(
                        (location) => DropdownMenuItem<String>(
                          value: location,
                          child: Text(location),
                        ),
                      )
                      .toList(),
                  onChanged: _saving
                      ? null
                      : (value) =>
                          setState(() => _locationController.text = value ?? ''),
                ),
                const SizedBox(height: 12),
                TextFormField(
                  controller: _brandController,
                decoration: InputDecoration(
                  labelText: context.l10n.brandLabel,
                  border: const OutlineInputBorder(),
                ),
                enabled: !_saving,
              ),
                const SizedBox(height: 12),
                Row(
                  children: [
                    Expanded(
                      child: OutlinedButton.icon(
                        onPressed: _saving ? null : () => _pickDate(false),
                        icon: const Icon(Icons.calendar_today, size: 16),
                        label: Text(
                          '${context.l10n.inventoryPurchaseDatePrefix}${_formatDate(_purchaseDate)}',
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: OutlinedButton.icon(
                        onPressed: _saving ? null : () => _pickDate(true),
                        icon: const Icon(Icons.event_available, size: 16),
                        label: Text(
                          '${context.l10n.inventoryBestBeforeDatePrefix}${_formatDate(_bestBeforeDate)}',
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ),
                  ],
                ),
                CheckboxListTile(
                  title: Text(context.l10n.openedLabel),
                  value: _opened,
                  onChanged: _saving
                      ? null
                      : (v) => setState(() => _opened = v ?? false),
                  controlAffinity: ListTileControlAffinity.leading,
                  contentPadding: EdgeInsets.zero,
                ),
                TextFormField(
                  controller: _commentController,
                  decoration: InputDecoration(
                    labelText: context.l10n.commentLabel,
                    border: const OutlineInputBorder(),
                  ),
                  maxLines: 2,
                  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.saveAction),
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}
