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

class MealListScreen extends StatefulWidget {
  static const String routeName = '/meals';

  const MealListScreen({Key? key}) : super(key: key);

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

class _MealListScreenState extends State<MealListScreen> {
  List<Meal> _meals = [];

  final ScrollController _scrollController = ScrollController();

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

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

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

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

  void handleDeleteAction(Meal 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 Scaffold(
      appBar: AppBar(title: const Text('Meals'), actions: <Widget>[
        IconButton(onPressed: reload, icon: const Icon(Icons.refresh))
      ]),
      drawer: const Navigation(currentLocation: MealListScreen.routeName),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Expanded(
            child: _meals.isNotEmpty ? Scrollbar(
              controller: _scrollController,
              child: ListView.builder(
                controller: _scrollController,
                padding: const EdgeInsets.all(10.0),
                itemCount: _meals.length,
                itemBuilder: (context, index) {
                  final meal = _meals[index];
                  String portionType = meal.mealPortionType.hasValue ? ' per ${meal.mealPortionType.target!.value}' : '';
                  return Card(
                    child: ListTile(
                      isThreeLine: true,
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) =>
                                MealDetailScreen(id: meal.id),
                          ),
                        ).then((result) => reload(message: result?[0]));
                      },
                      title: Text(
                        meal.value.toUpperCase(),
                        style: Theme.of(context).textTheme.subtitle2,
                      ),
                      subtitle: Padding(
                        padding: const EdgeInsets.symmetric(vertical: 10.0),
                        child: Column(
                          children: [
                            Row(
                              children: [
                                Expanded(
                                  child: Text(meal.mealSource.target?.value ?? ''),
                                ),
                                Expanded(
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    children: ((meal.carbsPerPortion ?? 0) > 0)
                                        ? [
                                            Text(meal.carbsPerPortion!.toStringAsPrecision(3)),
                                            Text(
                                              '${Settings.nutritionMeasurementSuffix} carbs',
                                              textScaleFactor: 0.75),
                                          ]
                                        : [],
                                  ),
                                ),
                                Expanded(
                                  child: Column(
                                    children: (meal.mealPortionType.hasValue)
                                      ? [
                                          Text(meal.portionSize?.toStringAsPrecision(3) ?? ''),
                                          Text(
                                            '${Settings.nutritionMeasurementSuffix}$portionType',
                                            textAlign: TextAlign.center,
                                            textScaleFactor: 0.75
                                          ),
                                        ]
                                      : [],
                                  ),
                                ),
                              ],
                            ),
                            meal.notes != null && meal.notes!.trim() != '' ? Padding(
                              padding: const EdgeInsets.only(top: 10.0),
                              child: Row(
                                children: [
                                  Expanded(child: Text(meal.notes ?? '')),
                                ],
                              ),
                            ) : Container(),
                          ],
                        ),
                      ),
                      trailing: Row(
                        mainAxisSize: MainAxisSize.min,
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          IconButton(
                            onPressed: () => handleDeleteAction(meal),
                            icon: const Icon(Icons.delete,
                                color: Colors.blue),
                          )
                        ],
                      ),
                    ),
                  );
                },
              ),
            ): const Center(
              child: Text('You have not created any Meals yet!'),
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => const MealDetailScreen(),
            ),
          ).then((result) => reload(message: result?[0]));
        },
        child: const Icon(Icons.add),
      ),
    );
  }
}
