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

class MealSourceListScreen extends StatefulWidget {
  static const String routeName = '/meal-sources';

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

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

class _MealSourceListScreenState extends State<MealSourceListScreen> {
  List<MealSource> _mealSources = [];

  final ScrollController _scrollController = ScrollController();

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

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

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

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

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

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