import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krezus/domains/account/account_bloc.dart';
import 'package:krezus/pages/common/titled_container.dart';
import 'package:krezus/repositories/metadata/models/account.dart';

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

  List<Widget> _computeCategoryList(BuildContext context, List<Account> accounts) {
    return accounts.map((account) => Row(
      children: [
        IconButton(
          onPressed: () {},
          icon: const Icon(Icons.palette),
          color: account.rgbToColor(),
        ),
        IconButton(
          onPressed: () => context.read<AccountBloc>().add(AccountEditSaving(account, !account.saving)),
          icon: const Icon(Icons.savings),
          color: account.saving ? Theme.of(context).colorScheme.primary : Theme.of(context).colorScheme.error,
        ),
        Container(width: 5),
        Expanded(
          child: Text(account.label)
        ),
        IconButton(
          onPressed: () {},
          icon: const Icon(Icons.edit),
        ),
        IconButton(
          onPressed: () => context.read<AccountBloc>().add(AccountRemove(account)),
          icon: const Icon(Icons.delete),
        ),
      ],
    )).toList();
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<AccountBloc, AccountState>(
      listener: (context, state) {
        if (state is AccountRemoveSucess) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              backgroundColor: Colors.green,
              content: Text('Account succesfuly removed !'),
            )
          );
        } else if (state is AccountRemoveFail) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              backgroundColor: Colors.red,
              content: Text('Cannot remove account. Still present on some transactions.'),
            )
          );
        }
      },
      builder: (context, state) => TitledContainer(
        title: "Accounts",
        action: IconButton(
          onPressed: () => context.read<AccountBloc>().add(AccountAdd()),
          icon: const Icon(Icons.add),
        ),
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: _computeCategoryList(context, state.accounts),
          ),
        ),
      ),
    );
  }
}