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

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

  List<Widget> _computeCategoryList(BuildContext context, List<Category> categories) {
    return categories.map((category) => Row(
      children: [
        IconButton(
          onPressed: () {},
          icon: const Icon(Icons.palette),
          color: category.rgbToColor(),
        ),
        IconButton(
          onPressed: () => context.read<CategoryBloc>().add(CategoryEditTransfert(category, !category.transfert)),
          icon: const Icon(Icons.swap_horiz),
          color: category.transfert ? Theme.of(context).colorScheme.primary : Theme.of(context).colorScheme.error,
        ),
        IconButton(
          onPressed: () => context.read<CategoryBloc>().add(CategoryEditEssential(category, !category.essential)),
          icon: const Icon(Icons.foundation),
          color: category.essential ? Theme.of(context).colorScheme.primary : Theme.of(context).colorScheme.error,
        ),
        Container(width: 5),
        Expanded(
          child: Text(category.label)
        ),
        IconButton(
          onPressed: () {},
          icon: const Icon(Icons.edit),
        ),
        IconButton(
          onPressed: () => context.read<CategoryBloc>().add(CategoryRemove(category)),
          icon: const Icon(Icons.delete),
        ),
      ],
    )).toList();
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<CategoryBloc, CategoryState>(
      listener: (context, state) {
        if (state is CategoryRemoveSucess) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              backgroundColor: Colors.green,
              content: Text('Category succesfuly removed !'),
            )
          );
        } else if (state is CategoryRemoveFail) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              backgroundColor: Colors.red,
              content: Text('Cannot remove category. Still present on some transactions.'),
            )
          );
        }
      },
      builder: (context, state) => TitledContainer(
        title: "Categories",
        action: IconButton(
          onPressed: () => context.read<CategoryBloc>().add(CategoryAdd()),
          icon: const Icon(Icons.add),
        ),
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: _computeCategoryList(context, state.categories),
          ),
        ),
      )
    );
  }
}