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

import '../../../core/api/api_error_mapper.dart';
import '../../../core/ui/async_state_views.dart';
import '../../auth/data/auth_providers.dart';
import '../data/shopping_list_providers.dart';
import '../domain/shopping_list_item.dart';

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final asyncItems = ref.watch(shoppingListItemsProvider);

    return asyncItems.when(
      loading: () => const LoadingStateView(label: 'Laddar inköpslista...'),
      error: (error, _) => ErrorStateView(
        message: mapErrorToUserMessage(error, context),
        onRetry: () => ref.invalidate(shoppingListItemsProvider),
      ),
      data: (items) {
        if (items.isEmpty) {
          return const EmptyStateView(
            title: 'Inköpslistan är tom',
            description: 'Planerade flyer-varor hamnar här.',
          );
        }

        return ListView.separated(
          padding: const EdgeInsets.all(12),
          itemCount: items.length,
          separatorBuilder: (_, __) => const SizedBox(height: 8),
          itemBuilder: (context, index) {
            final item = items[index];
            return _ShoppingListTile(item: item);
          },
        );
      },
    );
  }
}

class _ShoppingListTile extends ConsumerStatefulWidget {
  final ShoppingListItem item;

  const _ShoppingListTile({required this.item});

  @override
  ConsumerState<_ShoppingListTile> createState() => _ShoppingListTileState();
}

class _ShoppingListTileState extends ConsumerState<_ShoppingListTile> {
  bool _saving = false;

  Future<void> _checkOff() async {
    if (_saving) return;
    setState(() => _saving = true);
    try {
      final token = await ref.read(authStateProvider.future);
      await ref.read(shoppingListRepositoryProvider).updateStatus(
            itemId: widget.item.id,
            checked: true,
            token: token,
          );
      ref.invalidate(shoppingListItemsProvider);
    } catch (error) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        buildCopyableErrorSnackBar(context, mapErrorToUserMessage(error, context)),
      );
    } finally {
      if (mounted) setState(() => _saving = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final item = widget.item;

    return Card(
      child: ListTile(
        leading: _saving
            ? const SizedBox(
                width: 22,
                height: 22,
                child: CircularProgressIndicator(strokeWidth: 2),
              )
            : Checkbox(
                value: false,
                onChanged: (_) => _checkOff(),
              ),
        title: Text(item.name),
        subtitle: item.quantityLabel.isEmpty ? null : Text(item.quantityLabel),
      ),
    );
  }
}
