import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krow/core/presentation/widgets/ui_kit/check_box.dart';
import 'package:krow/core/presentation/widgets/ui_kit/check_box_card.dart';
import 'package:krow/features/check_list/domain/bloc/check_list_bloc.dart';
import 'package:krow/features/check_list/domain/bloc/check_list_event.dart';
import 'package:krow/features/check_list/domain/bloc/check_list_state.dart';

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

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<CheckListBloc, CheckListState>(
      buildWhen: (previous, current) {
        return previous.checkListItems != current.checkListItems;
      },
      builder: (context, state) {
        return Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            for (final item in state.checkListItems)
              CheckBoxCard(
                title: item.title,
                isChecked: item.error == null,
                checkBoxStyle: item.error != null
                    ? CheckBoxStyle.black
                    : CheckBoxStyle.green,
                padding: const EdgeInsets.only(top: 8),
                trailing: true,
                errorMessage: item.error,
                onTap: () {
                  final route = item.route;
                  if (route == null) return;

                  context.router.push<void>(route).then((_) {
                    if (!context.mounted) return;

                    context
                        .read<CheckListBloc>()
                        .add(CheckForListUpdateEvent(editedItem: item));
                  });
                },
              ),
          ],
        );
      },
    );
  }
}
