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

import '../../../../storage/base/settingsProvider.dart';
import '../../../../widget/confirmDialog.dart';

class GradeAverage extends StatefulWidget {
  const GradeAverage({super.key});

  @override
  State<GradeAverage> createState() => _GradeAverageState();
}

class _GradeAverageState extends State<GradeAverage> {
  double average = 0;
  bool gradeSystem = true;
  List<int> grades = List.empty(growable: true);

  late SettingsProvider settings = Provider.of<SettingsProvider>(context, listen: false);
  
  void _persistGrades() {
    settings.val(write: true).gradeAveragesSettings.inputs = grades;
  }

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

  void switchSystem(bool e) => setState(() {
    grades.clear();
    gradeSystem = e;
    settings.val(write: true).gradeAveragesSettings.useGradeSystem = e;
    _persistGrades();
  });

  @override
  void initState() {
    super.initState();
    
    grades = settings.val().gradeAveragesSettings.inputs;
    gradeSystem = settings.val().gradeAveragesSettings.useGradeSystem;

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      if(!settings.val().gradeAveragesSettings.askedForPreferredGradeSystem) {
        settings.val(write: true).gradeAveragesSettings.askedForPreferredGradeSystem = true;
        showDialog(context: context, builder: (context) => AlertDialog(
          title: const Text('Notensystem'),
          content: const Text('Wähle dein bevorzugtes Schulnotensystem'),
          actions: [
            TextButton(
              onPressed: () {
                switchSystem(true);
                Navigator.of(context).pop();
              },
              child: const Text('Realschule'),
            ),
            TextButton(
              onPressed: () {
                switchSystem(false);
                Navigator.of(context).pop();
              },
              child: const Text('Oberstufe'),
            ),
          ],
        ));
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    if(grades.isNotEmpty) {
       average = grades.reduce((a, b) => a + b) / grades.length;
    } else {
      average = 0;
    }

    return Scaffold(
      appBar: AppBar(
        title: const Text('Notendurschnittsrechner'),
        actions: [
          Visibility(
            visible: grades.isNotEmpty,
            child: IconButton(onPressed: () {
              showDialog(
                context: context,
                builder: (context) => ConfirmDialog(
                  title: 'Zurücksetzen?',
                  content: 'Alle Einträge werden entfernt.',
                  confirmButton: 'Zurücksetzen',
                  onConfirm: () {
                    grades.clear();
                    setState(() {});
                  },
                ),
              );
            }, icon: const Icon(Icons.delete_forever)),
          ),
          PopupMenuButton<bool>(
            initialValue: gradeSystem,
            icon: const Icon(Icons.more_horiz),
            itemBuilder: (context) => [true, false].map((e) => PopupMenuItem<bool>(
              value: e,
              child: Row(
                children: [
                  Icon(e ? Icons.calculate_outlined : Icons.school_outlined, color: Theme.of(context).colorScheme.onSurface),
                  const SizedBox(width: 15),
                  Text(e ? 'Notensystem' : 'Punktesystem'),
                ],
              ),
            )).toList(),

            onSelected: (e) {

              if(grades.isNotEmpty) {
                showDialog(
                  context: context,
                  builder: (context) => ConfirmDialog(
                    title: 'Notensystem wechseln',
                    content: 'Beim wechsel des Notensystems werden alle Einträge zurückgesetzt.',
                    confirmButton: 'Fortfahren',
                    onConfirm: () => switchSystem(e),
                  ),
                );
              } else {
                switchSystem(e);
              }
            },
          ),
        ],
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const SizedBox(height: 30),
          Text(average.toStringAsFixed(2), style: const TextStyle(fontSize: 30, fontWeight: FontWeight.bold)),
          const SizedBox(height: 10),
          const Divider(),
          const SizedBox(height: 10),
          Text(gradeSystem ? 'Wähle unten die Anzahl deiner jewiligen Noten aus' : 'Wähle unten die Anzahl deiner jeweiligen Punkte aus'),
          const SizedBox(height: 10),
          Expanded(
            child: ListView.builder(
              itemBuilder: (context, index) {
                var grade = gradeSystem ? index + 1 : 15 - index;
                bool isThis(int e) => e == grade;
                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(
                            onPressed: () {
                              setState(() {
                                if(!grades.any(isThis)) return;
                                grades.removeAt(grades.indexWhere(isThis));
                                _persistGrades();
                              });
                            },
                            icon: const Icon(Icons.remove),
                            color: Theme.of(context).colorScheme.onSurface,
                          ),
                          Text('${grades.where(isThis).length}', style: const TextStyle(fontSize: 15, fontWeight: FontWeight.bold)),
                          IconButton(
                            onPressed: () {
                              setState(() {
                                grades.add(grade);
                                _persistGrades();
                              });
                            },
                            icon: const Icon(Icons.add),
                            color: Theme.of(context).colorScheme.onSurface,
                          ),
                        ],
                      ),
                    ),
                    trailing: Visibility(
                      maintainState: true,
                      maintainAnimation: true,
                      maintainSize: true,
                      visible: grades.any(isThis),
                      child: IconButton(
                        icon: const Icon(Icons.delete),
                        onPressed: () {
                          setState(() {
                            grades.removeWhere(isThis);
                            _persistGrades();
                          });
                        },
                      ),
                    ),
                  ),
                );
              },
              itemCount: gradeSystem ? 6 : 16,
            ),
          ),
        ],
      ),
    );
  }
}
