import 'package:diameter/utils/dialog_utils.dart';
import 'package:diameter/models/settings.dart';
import 'package:diameter/navigation.dart';
import 'package:diameter/screens/accuracy_detail.dart';
import 'package:flutter/material.dart';
import 'package:diameter/models/accuracy.dart';

class AccuracyListScreen extends StatefulWidget {
  static const String routeName = '/accuracies';
  const AccuracyListScreen({Key? key}) : super(key: key);

  @override
  _AccuracyListScreenState createState() => _AccuracyListScreenState();
}

class _AccuracyListScreenState extends State<AccuracyListScreen> {
  List<Accuracy> _accuracies = Accuracy.getAll();

  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    reload();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void reload({String? message}) {
    setState(() {
      _accuracies = Accuracy.getAll();
    });

    setState(() {
      if (message != null) {
        var snackBar = SnackBar(
          content: Text(message),
          duration: const Duration(seconds: 2),
        );
        ScaffoldMessenger.of(context)
          ..removeCurrentSnackBar()
          ..showSnackBar(snackBar);
      }
    });
  }

  void onDelete(Accuracy accuracy) {
    Accuracy.remove(accuracy.id);
    reload();
  }

  void handleDeleteAction(Accuracy accuracy) async {
    if (Settings.get().showConfirmationDialogOnDelete) {
      DialogUtils.showConfirmationDialog(
        context: context,
        onConfirm: () => onDelete(accuracy),
        message: 'Are you sure you want to delete this Accuracy?',
      );
    } else {
      onDelete(accuracy);
    }
  }

  void handleToggleForPortionSizeAction(Accuracy accuracy) async {
    accuracy.forPortionSize = !accuracy.forPortionSize;
    Accuracy.put(accuracy);
    reload();
  }

  void handleToggleForCarbsRatioAction(Accuracy accuracy) async {
    accuracy.forCarbsRatio = !accuracy.forCarbsRatio;
    Accuracy.put(accuracy);
    reload();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Accuracies'),
        actions: <Widget>[
          IconButton(onPressed: reload, icon: const Icon(Icons.refresh))
        ],
      ),
      drawer: const Navigation(currentLocation: AccuracyListScreen.routeName),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Expanded(
            child: _accuracies.isNotEmpty
                ? Scrollbar(
                    controller: _scrollController,
                    child: ReorderableListView.builder(
                        padding: const EdgeInsets.all(10.0),
                        scrollController: _scrollController,
                        itemCount: _accuracies.length,
                        onReorder: (oldIndex, newIndex) {
                          Accuracy.reorder(_accuracies[oldIndex], newIndex);
                          reload();
                        },
                        itemBuilder: (context, index) {
                          final accuracy = _accuracies[index];
                          return Card(
                            key: Key(accuracy.id.toString()),
                            child: ListTile(
                              onTap: () {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) =>
                                        AccuracyDetailScreen(id: accuracy.id),
                                  ),
                                ).then((result) => reload(message: result?[0]));
                              },
                              title: Text(
                                accuracy.value.toUpperCase(),
                                style: Theme.of(context).textTheme.subtitle2,
                              ),
                              leading: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: const [
                                  Icon(Icons.reorder),
                                ],
                              ),
                              trailing: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  IconButton(
                                    icon: Icon(
                                      Icons.square_foot,
                                      color: accuracy.forPortionSize
                                          ? Theme.of(context)
                                              .toggleableActiveColor
                                          : Theme.of(context).highlightColor,
                                    ),
                                    onPressed: () =>
                                        handleToggleForPortionSizeAction(
                                            accuracy),
                                  ),
                                  IconButton(
                                    icon: Icon(
                                      Icons.pie_chart,
                                      color: accuracy.forCarbsRatio
                                          ? Theme.of(context)
                                              .toggleableActiveColor
                                          : Theme.of(context).highlightColor,
                                    ),
                                    onPressed: () =>
                                        handleToggleForCarbsRatioAction(
                                            accuracy),
                                  ),
                                  IconButton(
                                    icon: const Icon(Icons.delete),
                                    onPressed: () =>
                                        handleDeleteAction(accuracy),
                                  )
                                ],
                              ),
                            ),
                          );
                        }),
                  )
                : const Center(
                    child: Text('You have not created any Accuracies yet!'),
                  ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => const AccuracyDetailScreen(),
            ),
          ).then((result) => reload(message: result?[0]));
        },
        child: const Icon(Icons.add),
      ),
    );
  }
}
