import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krezus/domains/account/account_bloc.dart';
import 'package:krezus/domains/category/category_bloc.dart';
import 'package:krezus/domains/transaction/transaction_bloc.dart';
import 'package:krezus/pages/transactions/widgets/transaction_form.dart';
import 'package:krezus/repositories/transactions/models/transaction.dart';

class TransactionAddDialog extends StatelessWidget {
  const TransactionAddDialog({super.key});

  static void show(BuildContext context, Transaction? transaction) {
    context.read<TransactionBloc>().add(TransactionSetCurrent(transaction));
    showDialog(
      context: context,
      barrierDismissible: false,
      useRootNavigator: false,
      builder: (_) => MultiBlocProvider(
        providers: [
          BlocProvider.value(value: BlocProvider.of<TransactionBloc>(context)),
          BlocProvider.value(value: BlocProvider.of<CategoryBloc>(context)),
          BlocProvider.value(value: BlocProvider.of<AccountBloc>(context)),
        ],
        child: const TransactionAddDialog()
      )
    );
  }

  static void hide(BuildContext context) => Navigator.pop(context);

  _computeActions(BuildContext context, Transaction? currentTransaction) {
    final actions = [
      IconButton(
        onPressed: () => TransactionAddDialog.hide(context),
        icon: const Icon(Icons.close)
      ),
      IconButton(
        onPressed: () => context.read<TransactionBloc>().add(const TransactionAdd()),
        icon: const Icon(Icons.save)
      ),
    ];

    if (currentTransaction != null) {
      actions.add(IconButton(
        onPressed: () => context.read<TransactionBloc>().add(const TransactionDeleteCurrent()),
        icon: const Icon(Icons.delete)
      ));
    }

    return actions;
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<TransactionBloc, TransactionState>(
      buildWhen: (previous, current) => previous.currentTransaction != current.currentTransaction,
      builder: (context, state) => AlertDialog(
        title: Text(state.currentTransaction == null ? 'Add Transaction' : 'Edit Transaction'),
        actions: _computeActions(context, state.currentTransaction),
        content: const TransactionForm()
      )
    );
  }
}