import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../state/app/modules/grade_averages/bloc/grade_averages_bloc.dart';
import '../../../state/app/modules/grade_averages/bloc/grade_averages_event.dart';

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

  @override
  Widget build(BuildContext context) {
    var bloc = context.watch<GradeAveragesBloc>();

    String getGradeDisplay(int grade) {
      if (bloc.isMiddleSchool()) {
        return 'Note $grade';
      } else {
        return "$grade Punkt${grade > 1 ? "e" : ""}";
      }
    }

    return ListView.builder(
      itemCount: bloc.gradesInGradingSystem(),
      itemBuilder: (context, index) {
        var grade = bloc.getGradeFromIndex(index);
        return Material(
          child: ListTile(
            tileColor: grade.isEven
                ? Colors.transparent
                : Colors.transparent.withAlpha(50),
            title: Center(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(getGradeDisplay(grade)),
                  const SizedBox(width: 30),
                  IconButton(
                    tooltip: 'Note entfernen',
                    onPressed: () {
                      bloc.add(DecrementGrade(grade));
                    },
                    icon: const Icon(Icons.remove),
                    color: Theme.of(context).colorScheme.onSurface,
                  ),
                  Text(
                    '${bloc.countOfGrade(grade)}',
                    style: const TextStyle(
                      fontSize: 15,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  IconButton(
                    tooltip: 'Note hinzufügen',
                    onPressed: () {
                      bloc.add(IncrementGrade(grade));
                    },
                    icon: const Icon(Icons.add),
                    color: Theme.of(context).colorScheme.onSurface,
                  ),
                ],
              ),
            ),
            trailing: Visibility(
              maintainState: true,
              maintainAnimation: true,
              maintainSize: true,
              visible: bloc.canDecrementOrDelete(grade),
              child: IconButton(
                tooltip: 'Löschen',
                icon: const Icon(Icons.delete),
                onPressed: () {
                  bloc.add(ResetGrade(grade));
                },
              ),
            ),
          ),
        );
      },
    );
  }
}
