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 'package:skillcourt/dao/club_dao.dart';
import 'package:skillcourt/dao/group_dao.dart';
import 'package:skillcourt/entity/group.dart';
import 'package:skillcourt/pages/group_registration.dart';
import 'package:skillcourt/services/database.dart';
import 'package:skillcourt/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<List<dynamic>> doubleFuture() async {
    final ClubDao clubDao = database.clubDao;
    final GroupDao groupDao = database.groupDao;

    final clubs = await clubDao.findAllClubs();
    final groups = await groupDao.findAllGroups();

    return [clubs, groups];
  }

  @override
  Widget build(BuildContext context) {
    final GroupDao groupDao = database.groupDao;
    return FutureBuilder(
        future: doubleFuture(),
        builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
          final List<Widget> actions = [
            IconButton(
                icon: Icon(context.platformIcons.group),
                onPressed: () {
                  if (snapshot.hasData) {
                    final List clubList = snapshot.data![0] as List;
                    if (clubList.isEmpty) {
                      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![1] as List<Group>).length,
                      padding: const EdgeInsets.all(8.0),
                      itemBuilder: (BuildContext context, int index) {
                        final List<Group> groups =
                            snapshot.data![1].elementAt(index) as List<Group>;
                        List<Widget> children = [];
                        for (final Group group in groups) {
                          final child = Row(children: [
                            Expanded(
                                flex: 2,
                                child: Padding(
                                    padding: const EdgeInsets.fromLTRB(
                                        5.0, 0.0, 0.0, 0.0),
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(groups.elementAt(index).name,
                                            style: const TextStyle(
                                                fontWeight: FontWeight.bold,
                                                fontSize: 14)),
                                        Text(
                                            groups.elementAt(index).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(groups.elementAt(index));
                                  setState(() => {});
                                })
                          ]);

                          children.add(child);
                        }

                        return Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              ListView(
                                children: children,
                              )
                            ]);
                      },
                      separatorBuilder: (BuildContext context, int index) =>
                          const Divider())
                  : const Center(child: Text('No Players Registered')));
        });
  }
}
