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/ui/async_state_views.dart';
import '../data/inventory_providers.dart';
import 'swipeable_inventory_tile.dart';

class InventoryScreen extends ConsumerWidget {
  const InventoryScreen({super.key});

  static const _locationOptions = <String>['', 'Kyl', 'Frys', 'Skafferi'];
  static const _sortOptions = <({String value, String label})>[
    (value: '', label: 'Senast tillagda'),
    (value: 'nameAsc', label: 'Namn A-Ö'),
    (value: 'bestBeforeAsc', label: 'Bäst före stigande'),
    (value: 'bestBeforeDesc', label: 'Bäst före fallande'),
  ];

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final location = ref.watch(inventoryLocationFilterProvider);
    final sort = ref.watch(inventorySortFilterProvider);
    final inventoryAsync = ref.watch(inventoryProvider);

    return inventoryAsync.when(
      loading: () => const LoadingStateView(label: 'Laddar inventarie...'),
      error: (e, _) => ErrorStateView(
        message: mapErrorToUserMessage(e, context),
        onRetry: () => ref.invalidate(inventoryProvider),
      ),
      data: (items) {
        final filterSection = Padding(
          padding: const EdgeInsets.fromLTRB(12, 12, 12, 4),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                'Filter och sortering',
                style: TextStyle(fontWeight: FontWeight.w600),
              ),
              const SizedBox(height: 8),
              Wrap(
                spacing: 8,
                runSpacing: 8,
                children: _locationOptions
                    .map(
                      (option) => ChoiceChip(
                        label: Text(option.isEmpty ? 'Alla' : option),
                        selected: location == option,
                        onSelected: (_) => ref
                            .read(inventoryLocationFilterProvider.notifier)
                            .setValue(option),
                      ),
                    )
                    .toList(),
              ),
              const SizedBox(height: 8),
              DropdownButtonFormField<String>(
                initialValue: sort,
                isExpanded: true,
                decoration: const InputDecoration(
                  labelText: 'Sortering',
                  border: OutlineInputBorder(),
                ),
                items: _sortOptions
                    .map(
                      (option) => DropdownMenuItem<String>(
                        value: option.value,
                        child: Text(option.label),
                      ),
                    )
                    .toList(),
                onChanged: (value) {
                  ref
                      .read(inventorySortFilterProvider.notifier)
                      .setValue(value ?? '');
                },
              ),
            ],
          ),
        );

        if (items.isEmpty) {
          return Stack(
            children: [
              ListView(
                padding: const EdgeInsets.only(bottom: 88),
                children: [
                  filterSection,
                  const EmptyStateView(title: 'Inventariet är tomt.'),
                ],
              ),
              Positioned(
                right: 16,
                bottom: 16,
                child: FloatingActionButton.extended(
                  onPressed: () => context.push('/inventory/create'),
                  icon: const Icon(Icons.add),
                  label: const Text('Lägg till'),
                ),
              ),
            ],
          );
        }
        return Stack(
          children: [
            ListView.separated(
              padding: const EdgeInsets.only(bottom: 88),
              itemCount: items.length + 1,
              separatorBuilder: (_, __) => const Divider(height: 1),
              itemBuilder: (context, index) {
                if (index == 0) return filterSection;
                final item = items[index - 1];
                return SwipeableInventoryTile(item: item);
              },
            ),
            Positioned(
              right: 16,
              bottom: 16,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  FloatingActionButton.extended(
                    onPressed: () => context.push('/inventory/create'),
                    icon: const Icon(Icons.add),
                    label: const Text('Lägg till'),
                  ),
                  const SizedBox(height: 8),
                  FloatingActionButton.extended(
                    onPressed: () => context.go('/recipes'),
                    icon: const Icon(Icons.restaurant_menu),
                    label: const Text('Recept'),
                  ),
                ],
              ),
            ),
          ],
        );
      },
    );
  }
}


