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

import '../../../core/api/api_error_mapper.dart';
import '../../../core/l10n/l10n.dart';
import '../../../core/ui/async_state_views.dart';
import '../data/inventory_providers.dart';
import '../domain/inventory_consumption.dart';

class ConsumptionHistoryScreen extends ConsumerWidget {
  final int itemId;

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final historyAsync = ref.watch(consumptionHistoryProvider(itemId));
    final itemAsync = ref.watch(inventoryDetailProvider(itemId));

    return Scaffold(
      appBar: AppBar(
        title: itemAsync.maybeWhen(
          data: (item) => Text(context.l10n.inventoryHistoryTitle(item.productName)),
          orElse: () => Text(context.l10n.inventoryHistoryAction),
        ),
      ),
      body: historyAsync.when(
        loading: () => LoadingStateView(label: context.l10n.inventoryHistoryLoading),
        error: (e, _) => ErrorStateView(
          message: mapErrorToUserMessage(e, context),
          onRetry: () => ref.invalidate(consumptionHistoryProvider(itemId)),
        ),
        data: (history) {
          if (history.isEmpty) {
            return EmptyStateView(
              title: context.l10n.inventoryHistoryEmpty,
            );
          }
          return ListView.separated(
            itemCount: history.length,
            separatorBuilder: (_, __) => const Divider(height: 1),
            itemBuilder: (context, index) {
              final entry = history[index];
              return _HistoryTile(entry: entry);
            },
          );
        },
      ),
    );
  }
}

class _HistoryTile extends StatelessWidget {
  final InventoryConsumption entry;

  const _HistoryTile({required this.entry});

  @override
  Widget build(BuildContext context) {
    final dateStr =
        '${entry.createdAt.year}-${entry.createdAt.month.toString().padLeft(2, '0')}-${entry.createdAt.day.toString().padLeft(2, '0')}';
    final timeStr =
        '${entry.createdAt.hour.toString().padLeft(2, '0')}:${entry.createdAt.minute.toString().padLeft(2, '0')}';

    return ListTile(
      leading: const Icon(Icons.remove_circle_outline),
      title: Text('${entry.amountUsed} ${entry.unit}'),
      subtitle: entry.comment != null && entry.comment!.isNotEmpty
          ? Text(entry.comment!)
          : null,
      trailing: Text(
        '$dateStr $timeStr',
        style: Theme.of(context).textTheme.bodySmall,
      ),
    );
  }
}
