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

class MealCategoryListScreen extends StatefulWidget {
  static const String routeName = '/meal-categories';

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

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

class _MealCategoryListScreenState extends State<MealCategoryListScreen> {
  List<MealCategory> _mealCategories = [];

  final ScrollController _scrollController = ScrollController();

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

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

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

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Meal Categories'),
        actions: <Widget>[
          IconButton(
            onPressed: reload,
            icon: const Icon(Icons.refresh),
          ),
        ],
      ),
      drawer:
          const Navigation(currentLocation: MealCategoryListScreen.routeName),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Expanded(
            child: _mealCategories.isNotEmpty ? Scrollbar(
              controller: _scrollController,
              child: ListView.builder(
                controller: _scrollController,
                padding: const EdgeInsets.all(10.0),
                itemCount: _mealCategories.length,
                itemBuilder: (context, index) {
                  final mealCategory = _mealCategories[index];
                  return Card(
                    child: ListTile(
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) =>
                              MealCategoryDetailScreen(
                                id: mealCategory.id,
                            ),
                          ),
                        ).then((result) => reload(message: result?[0]));
                      },
                      title: Text(
                        mealCategory.value.toUpperCase(),
                        style: Theme.of(context).textTheme.subtitle2,
                      ),
                      trailing: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          IconButton(
                            icon: const Icon(
                              Icons.delete,
                              color: Colors.blue,
                            ),
                            onPressed: () =>
                                handleDeleteAction(mealCategory),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            ): const Center(
              child: Text('You have not created any Meal Categories yet!'),
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => const MealCategoryDetailScreen(),
            ),
          ).then((result) => reload(message: result?[0]));
        },
        child: const Icon(Icons.add),
      ),
    );
  }
}
