import 'package:diameter/utils/dialog_utils.dart';
import 'package:diameter/models/log_entry.dart';
import 'package:diameter/models/log_meal.dart';
import 'package:diameter/models/settings.dart';
import 'package:diameter/screens/log/log_entry/log_meal_detail.dart';
import 'package:flutter/material.dart';

class LogMealListScreen extends StatefulWidget {
  final LogEntry logEntry;
  final List<LogMeal> logMeals;
  final Function() reload;

  const LogMealListScreen(
      {Key? key, required this.logEntry, this.logMeals = const [], required this.reload})
      : super(key: key);

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

class _LogMealListScreenState extends State<LogMealListScreen> {
  final ScrollController _scrollController = ScrollController();

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

  void reload({String? message}) {
    widget.reload();

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

  void handleEditAction(LogMeal meal) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => LogMealDetailScreen(
          logEntryId: widget.logEntry.id,
          id: meal.id,
        ),
      ),
    ).then((result) => reload(message: result?[0]));
  }

  void onDelete(LogMeal logMeal) {
    LogMeal.remove(logMeal.id);
    reload(message: 'Meal deleted');
  }

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

  @override
  Widget build(BuildContext context) {
    return widget.logMeals.isNotEmpty
        ? Scrollbar(
          controller: _scrollController,
          child: ListView.builder(
              padding: const EdgeInsets.all(10.0),
              controller: _scrollController,
              shrinkWrap: true,
              itemCount: widget.logMeals.length,
              itemBuilder: (context, index) {
                final meal = widget.logMeals[index];
                return Card(
                  child: ListTile(
                    onTap: () => handleEditAction(meal),
                    title: Row(
                      children: [
                        Expanded(child: Text(
                          meal.value.toUpperCase(),
                          style: Theme.of(context).textTheme.subtitle2,
                        )),
                        Expanded(
                          child: Column(
                            children: ((meal.totalCarbs ?? 0) > 0)
                                ? [
                                    Text(meal.totalCarbs!.toStringAsPrecision(3)),
                                    Text(
                                      '${Settings.nutritionMeasurementSuffix} carbs',
                                      textScaleFactor: 0.75),
                                  ]
                                : [],
                            ),
                          ),
                      ],
                    ),
                    trailing: IconButton(
                      icon: const Icon(
                        Icons.delete,
                        color: Colors.blue,
                      ),
                      onPressed: () => handleDeleteAction(meal),
                    ),
                  ),
                );
              },
            ),
        )
        : const Center(
            child: Text(
                'You have not added any Meals to this Log Entry yet!'),
          );
  }
}
