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/api/api_paths.dart';
import '../../../core/api/api_providers.dart';
import '../../../core/forms/form_options.dart';
import '../../../core/l10n/l10n.dart';
import '../../../core/ui/product_picker_field.dart';
import '../../auth/data/auth_providers.dart';
import '../data/inventory_providers.dart';

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

  @override
  ConsumerState<CreateInventoryScreen> createState() =>
      _CreateInventoryScreenState();
}

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

  int? _selectedProductId;
  List<Map<String, dynamic>> _products = [];
  bool _loadingProducts = false;
  DateTime? _purchaseDate;
  DateTime? _bestBeforeDate;
  bool _opened = false;
  bool _saving = false;

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

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

  Future<void> _loadProducts() async {
    setState(() => _loadingProducts = true);
    try {
      final token = await ref.read(authStateProvider.future);
      final api = ref.read(apiClientProvider);
      final data = await api.getJson(ProductApiPaths.list, token: token);
      final list = data is List<dynamic>
          ? data
          : (data is Map<String, dynamic> && data['items'] is List<dynamic>)
              ? data['items'] as List<dynamic>
              : const <dynamic>[];
      if (mounted) {
        setState(() {
          _products = list
              .map((e) => e as Map<String, dynamic>)
              .toList();
          _loadingProducts = false;
        });
      }
    } catch (e) {
      if (mounted) setState(() => _loadingProducts = false);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(mapErrorToUserMessage(e, context))),
        );
      }
    }
  }

  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;
    if (_selectedProductId == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(context.l10n.inventorySelectProduct)),
      );
      return;
    }
    setState(() => _saving = true);
    try {
      final token = await ref.read(authStateProvider.future);
      final body = <String, dynamic>{
        'productId': _selectedProductId,
        'quantity':
            double.parse(_quantityController.text.trim().replaceAll(',', '.')),
        'unit': _unitController.text.trim(),
        if (_locationController.text.trim().isNotEmpty)
          'location': _locationController.text.trim(),
        if (_brandController.text.trim().isNotEmpty)
          'brand': _brandController.text.trim(),
        if (_purchaseDate != null)
          'purchaseDate': _purchaseDate!.toIso8601String(),
        if (_bestBeforeDate != null)
          'bestBeforeDate': _bestBeforeDate!.toIso8601String(),
        'opened': _opened,
        if (_commentController.text.trim().isNotEmpty)
          'comment': _commentController.text.trim(),
      };
      await ref
          .read(inventoryRepositoryProvider)
          .createInventoryItem(body, token: token);
      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 sortedProducts = [..._products]
      ..sort((a, b) {
        final aName = (a['canonicalName'] ?? a['name'] ?? '').toString();
        final bName = (b['canonicalName'] ?? b['name'] ?? '').toString();
        return aName.toLowerCase().compareTo(bName.toLowerCase());
      });
    final productOptions = sortedProducts
        .map(
          (p) => (
            id: (p['id'] as num).toInt(),
            name: (p['canonicalName'] ?? p['name'] ?? '').toString(),
            categoryId: (p['categoryId'] as num?)?.toInt(),
          ),
        )
        .toList();

    return Scaffold(
      appBar: AppBar(title: Text(context.l10n.inventoryCreateTitle)),
      body: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(16),
          children: [
            ProductPickerField(
              products: productOptions,
              value: _selectedProductId,
              isLoading: _loadingProducts,
              enabled: !_saving,
              label: context.l10n.inventoryProductLabel,
              onChanged: (value) => setState(() => _selectedProductId = value),
            ),
            const SizedBox(height: 12),
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  flex: 2,
                  child: TextFormField(
                    controller: _quantityController,
                    decoration: InputDecoration(
                      labelText: context.l10n.quantityLabel,
                      border: const OutlineInputBorder(),
                    ),
                    keyboardType: const TextInputType.numberWithOptions(
                        decimal: true),
                    enabled: !_saving,
                    validator: (v) {
                      if (v == null || v.trim().isEmpty) return context.l10n.quantityHint;
                      if (double.tryParse(v.trim().replaceAll(',', '.')) ==
                          null) {
                        return context.l10n.invalidNumber;
                      }
                      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: (value) =>
                        (value == null || value.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.locationOptionalLabel,
                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.brandOptionalLabel,
                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.commentOptionalLabel,
                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),
                    )
                  : const Text('Spara'),
            ),
          ],
        ),
      ),
    );
  }
}
