import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krezus/domains/account/account_bloc.dart';
import 'package:krezus/domains/transaction/transaction_bloc.dart';
import 'package:krezus/repositories/metadata/models/account.dart';

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

  @override
  Widget build(BuildContext context) {
    final accountState = context.watch<AccountBloc>().state;

    return BlocBuilder<TransactionBloc, TransactionState>(
      buildWhen: (previous, current) => previous.accountFilter != current.accountFilter,
      builder: (context, state) => SizedBox(
        width: 300,
        child: DropdownButtonFormField<Account>(
          value: state.accountFilter,
          onChanged: (value) => context.read<TransactionBloc>().add(TransactionFilterAccount(value!)),
          items: accountState.accounts.map((e) => DropdownMenuItem(value: e, child: Text(e.label))).toList(),
          decoration: InputDecoration(
            suffixIcon: IconButton(
              icon: const Icon(Icons.filter_alt_off),
              onPressed: () => context.read<TransactionBloc>().add(const TransactionFilterAccount(null)),
            ),
            hintText: 'Account',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(5),
            ),
          ),
        ),
      ),
    );
  }
}