import 'package:diameter/utils/dialog_utils.dart';
import 'package:diameter/models/settings.dart';
import 'package:diameter/utils/date_time_utils.dart';
import 'package:flutter/material.dart';
import 'package:diameter/models/basal.dart';
import 'package:diameter/models/basal_profile.dart';
import 'package:diameter/screens/basal/basal_detail.dart';

class BasalListScreen extends StatefulWidget {
  final BasalProfile basalProfile;
  final List<Basal> basalRates;
  final Function() reload;

  const BasalListScreen(
      {Key? key,
      required this.basalProfile,
      this.basalRates = const [],
      required this.reload})
      : super(key: key);

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

class _BasalListScreenState extends State<BasalListScreen> {
  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(Basal basal) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => BasalDetailScreen(
          basalProfileId: widget.basalProfile.id,
          id: basal.id,
        ),
      ),
    ).then((result) => reload(message: result?[0]));
  }

  void onDelete(Basal basal) {
    Basal.remove(basal.id);
    reload(message: 'Basal Rate deleted');
  }

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

  String? validateTimePeriod(int index) {
    List<Basal> basalRates = widget.basalRates;
    Basal basal = basalRates[index];

    // check for gaps
    if (index == 0 &&
        (basal.startTime.hour != 0 || basal.startTime.minute != 0)) {
      return 'First Basal of the day needs to start at 00:00';
    }

    if (index > 0) {
      var lastEndTime = basalRates[index - 1].endTime;
      if (basal.startTime.isAfter(lastEndTime)) {
        return 'There\'s a time gap between this and the previous rate';
      }
    }

    if (index == basalRates.length - 1 &&
        (basal.endTime.hour != 0 || basal.endTime.minute != 0)) {
      return 'Last Basal of the day needs to end at 00:00';
    }

    // check for duplicates
    if (basalRates
        .where((other) => basal != other && basal.startTime == other.startTime)
        .isNotEmpty) {
      return 'There are multiple rates with this start time';
    }

    if (basalRates
        .where((other) =>
            basal.startTime.isBefore(other.startTime) &&
            basal.endTime.isAfter(other.startTime))
        .isNotEmpty) {
      return 'This rate\'s time period overlaps with another one';
    }

    return null;
  }

  @override
  Widget build(BuildContext context) {
    return widget.basalRates.isNotEmpty
        ? Scrollbar(
            controller: _scrollController,
            child: ListView.builder(
              padding: const EdgeInsets.all(10.0),
              controller: _scrollController,
              shrinkWrap: true,
              itemCount: widget.basalRates.length,
              itemBuilder: (context, index) {
                final basal = widget.basalRates[index];
                final error = validateTimePeriod(index);
                return Card(
                  child: Column(
                    children: [
                      error != null
                          ? Padding(
                              padding: const EdgeInsets.all(5.0),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Icon(Icons.warning,
                                      color: Theme.of(context).errorColor),
                                  Text(error,
                                      style: TextStyle(
                                          color: Theme.of(context).errorColor)),
                                ],
                              ),
                            )
                          : Container(),
                      ListTile(
                        onTap: () {
                          handleEditAction(basal);
                        },
                        title: Row(
                          mainAxisSize: MainAxisSize.max,
                          children: [
                            Expanded(
                                child: Text(
                                    '${DateTimeUtils.displayTime(basal.startTime)} - ${DateTimeUtils.displayTime(basal.endTime)}')),
                            const Spacer(),
                            Expanded(child: Text('${basal.units} U')),
                          ],
                        ),
                        trailing: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            IconButton(
                              icon: const Icon(
                                Icons.delete,
                                color: Colors.blue,
                              ),
                              onPressed: () => handleDeleteAction(basal),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                );
              },
            ),
          )
        : const Center(
            child: Text('You have not created any Basal Rates yet!'),
          );
  }
}
