import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_platform_widgets/flutter_platform_widgets.dart';
import 'package:get_it/get_it.dart';

import './group_registration.dart';
import '../dao/club_dao.dart';
import '../dao/group_dao.dart';
import '../entity/group.dart';
import '../services/database.dart';
import '../widgets/labeled_icon_button.dart';

final getIt = GetIt.instance;

class GroupList extends StatefulWidget {
  static const String routeName = 'group-list';

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

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

class _GroupListState extends State<GroupList> {
  final DatabaseService database = getIt<DatabaseService>();

  final _title = 'Registered Groups';

  Future<Map<String, dynamic>> _data() async {
    final GroupDao groupDao = database.groupDao;
    final ClubDao clubDao = database.clubDao;

    final List<Group> groups = await groupDao.findAllGroups();
    final int clubCount = await clubDao.countClubs() as int;

    return {'groups': groups, 'clubCount': clubCount};
  }

  @override
  Widget build(BuildContext context) {
    final GroupDao groupDao = database.groupDao;

    return FutureBuilder<Map<String, dynamic>>(
        future: _data(),
        builder: (BuildContext context,
            AsyncSnapshot<Map<String, dynamic>> snapshot) {
          final List<Widget> actions = [
            IconButton(
                icon: Icon(context.platformIcons.group),
                onPressed: () {
                  if (snapshot.hasData) {
                    final clubCount = snapshot.data!['clubCount'] as int;

                    if (clubCount == 0) {
                      showPlatformDialog(
                          context: context,
                          builder: (_) => PlatformAlertDialog(
                                  title: const Text('No Clubs Are Registered'),
                                  content: const Text(
                                      'At least one club must be registered in the application to create a group'),
                                  actions: <Widget>[
                                    PlatformDialogAction(
                                      onPressed: () => Navigator.pop(context),
                                      child: PlatformText('Ok'),
                                    )
                                  ]));
                    } else {
                      Navigator.pushNamed(context, GroupRegistration.routeName,
                              arguments: GroupRegistrationArguments(-1))
                          .then((value) => setState(() {}));
                    }
                  }
                })
          ];

          return PlatformScaffold(
              appBar: PlatformAppBar(
                title: Text(_title),
                trailingActions: actions,
              ),
              body: (snapshot.hasData)
                  ? ListView.separated(
                      itemCount:
                          (snapshot.data!['groups'] as List<Group>).length,
                      padding: const EdgeInsets.all(8.0),
                      itemBuilder: (BuildContext context, int index) {
                        final List<Group> groups =
                            snapshot.data!['groups'] as List<Group>;
                        final Group group = groups.elementAt(index);

                        return Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Expanded(
                                flex: 2,
                                child: Padding(
                                    padding: const EdgeInsets.fromLTRB(
                                        5.0, 0.0, 0.0, 0.0),
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(group.name,
                                            style: const TextStyle(
                                                fontWeight: FontWeight.bold,
                                                fontSize: 14)),
                                        Text(group.description)
                                      ],
                                    ))),
                            LabeledIconButton(
                                width: 60.0,
                                label: 'Edit',
                                iconData: context.platformIcons.edit,
                                materialColor: Colors.green,
                                cupertinoColor: CupertinoColors.systemGreen,
                                onPressed: () => Navigator.pushNamed(
                                        context, GroupRegistration.routeName,
                                        arguments: GroupRegistrationArguments(
                                            group.id!))
                                    .then((value) => setState(() {}))),
                            LabeledIconButton(
                                width: 84.0,
                                label: 'Remove',
                                iconData: context.platformIcons.delete,
                                materialColor: Colors.red,
                                cupertinoColor: CupertinoColors.systemRed,
                                onPressed: () async {
                                  await groupDao.deleteGroup(group);
                                  setState(() => {});
                                })
                          ],
                        );
                      },
                      separatorBuilder: (BuildContext context, int index) =>
                          const Divider())
                  : const Center(child: Text('No Groups Registered')));
        });
  }
}
