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

class MealPortionTypeListScreen extends StatefulWidget {
  static const String routeName = '/meal-portion-types';

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

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

class _MealPortionTypeListScreenState extends State<MealPortionTypeListScreen> {
  List<MealPortionType> _mealPortionTypes = [];

  final ScrollController _scrollController = ScrollController();

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

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

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

  void onDelete(MealPortionType mealPortionType) {
    MealPortionType.remove(mealPortionType.id);
    reload(message: 'Meal Portion Type deleted');
  }

  void handleDeleteAction(MealPortionType mealPortionType) async {
    if (Settings.get().showConfirmationDialogOnDelete) {
      DialogUtils.showConfirmationDialog(
        context: context,
        onConfirm: () => onDelete(mealPortionType),
        message: 'Are you sure you want to delete this Meal Portion Type?',
      );
    } else {
      onDelete(mealPortionType);
    }
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Meal Portion Types'),
        actions: <Widget>[
          IconButton(onPressed: reload, icon: const Icon(Icons.refresh))
        ],
      ),
      drawer: const Navigation(
          currentLocation: MealPortionTypeListScreen.routeName),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Expanded(
            child: _mealPortionTypes.isNotEmpty ? Scrollbar(
              controller: _scrollController,
              child: ListView.builder(
                controller: _scrollController,
                padding: const EdgeInsets.all(10.0),
                itemCount: _mealPortionTypes.length,
                itemBuilder: (context, index) {
                  final mealPortionType = _mealPortionTypes[index];
                  return Card(
                    child: ListTile(
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) =>
                              MealPortionTypeDetailScreen(
                                id: mealPortionType.id,
                            ),
                          ),
                        ).then(
                            (message) => reload(message: message));
                      },
                      title: Text(
                        mealPortionType.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(mealPortionType),
                          ),
                        ],
                      ),
                    ),
                  );
                },
                ),
            ) : const Center(
              child: Text('You have not created any Meal Portion Types yet!'),
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => const MealPortionTypeDetailScreen(),
            ),
          ).then((result) => reload(message: result?[0]));
        },
        child: const Icon(Icons.add),
      ),
    );
  }
}
