import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:moneymgr_mobile/services/router/routes_list.dart';
import 'package:moneymgr_mobile/services/storage/expenses.dart';
import 'package:moneymgr_mobile/utils/time_utils.dart';
import 'package:moneymgr_mobile/widgets/full_screen_error.dart';
import 'package:moneymgr_mobile/widgets/loading_scaffold.dart';
import 'package:moneymgr_mobile/widgets/synchronize_button.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'scans_list_screen.g.dart';

@riverpod
Future<ExpensesList> _expensesList(Ref ref) {
  final expenses = ref.watch(expensesProvider).requireValue;
  return expenses.getList();
}

class ScansListScreen extends HookConsumerWidget {
  const ScansListScreen({super.key});

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

    return switch (expensesList) {
      AsyncData(:final value) => Scaffold(
        appBar: AppBar(
          title: Text("Expenses"),
          actions: [value.isEmpty ? Container() : SynchronizeButton()],
        ),
        body: _ExpensesList(list: value),
      ),
      AsyncError(:final error) => FullScreenError(
        message: "Failed to load the list of expenses",
        error: error.toString(),
      ),
      _ => const LoadingScaffold(title: "Expenses"),
    };
  }
}

class _ExpensesList extends StatelessWidget {
  final ExpensesList list;

  const _ExpensesList({required this.list});

  @override
  Widget build(BuildContext context) {
    if (list.isEmpty) {
      return const Center(
        child: Text("There is no entry waiting for upload (yet)"),
      );
    }

    return ListView.builder(
      itemBuilder: (context, entryNum) {
        final expense = list[entryNum];
        return ListTile(
          onTap: () => context.push("$scansPage/${expense.id}"),
          leading: Icon(Icons.receipt_long),
          title: Text(
            expense.label ?? "No label",
            style: TextStyle(
              fontStyle: expense.label == null ? FontStyle.italic : null,
            ),
          ),
          subtitle: Text(expense.dateTime.simpleDate),
          trailing: Text("${expense.cost} €", style: TextStyle(fontSize: 20)),
        );
      },
      itemCount: list.length,
    );
  }
}
