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

class LogBolusListScreen extends StatefulWidget {
  final LogEntry logEntry;
  final List<LogBolus> logBoli;
  final Function() reload;

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

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

class _LogBolusListScreenState extends State<LogBolusListScreen> {
  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(LogBolus logBolus) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => LogBolusDetailScreen(
          logEntryId: widget.logEntry.id,
          id: logBolus.id,
        ),
      ),
    ).then((result) => reload(message: result?[0]));
  }

  void onDelete(LogBolus logBolus) {
    LogBolus.remove(logBolus.id);
    reload(message: 'Bolus deleted');
  }

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

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

  @override
  Widget build(BuildContext context) {
    return widget.logBoli.isNotEmpty
        ? Scrollbar(
          controller: _scrollController,
          child: ListView.builder(
            padding: const EdgeInsets.all(10.0),
              controller: _scrollController,
              shrinkWrap: true,
              itemCount: widget.logBoli.length,
              itemBuilder: (context, index) {
                final bolus = widget.logBoli[index];
                String titleText = '${bolus.units} U ${(bolus.delay ?? 0) != 0
                          ? ' (delayed by ${bolus.delay} min)'
                          : ''}';
                return Card(
                  child: ListTile(
                    onTap: () => handleEditAction(bolus),
                    title: Text(
                      titleText.toUpperCase(),
                      style: Theme.of(context).textTheme.subtitle2,
                    ),
                    subtitle: Text(bolus.carbs != null ?
                        'for ${(bolus.meal.target ?? '').toString()} (${bolus.carbs}${Settings.nutritionMeasurementSuffix} carbs)'
                        : 'to correct ${Settings.glucoseMeasurement == GlucoseMeasurement.mgPerDl ? bolus.mgPerDlCorrection : bolus.mmolPerLCorrection} ${Settings.glucoseMeasurementSuffix}'),
                    trailing: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        bolus.meal.target != null
                            ? IconButton(
                                icon: const Icon(Icons.restaurant),
                                onPressed: () =>
                                    handleEditMealAction(bolus.meal.targetId),
                              )
                            : Container(),
                        const SizedBox(width: 24),
                        IconButton(
                          icon: const Icon(
                            Icons.delete,
                            color: Colors.blue,
                          ),
                          onPressed: () => handleDeleteAction(bolus),
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
        )
        : const Center(
            child: Text(
                'You have not added any Boli to this Log Entry yet!'),
          );
  }
}
