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/club.dart';
import 'package:skillcourt/entity/group.dart';
import 'package:skillcourt/pages/group_list.dart';
import 'package:skillcourt/services/database.dart';
import 'package:skillcourt/widgets/text_field.dart';

final getIt = GetIt.instance;

class GroupRegistrationArguments {
  final int id;

  GroupRegistrationArguments(this.id);
}

class GroupRegistration extends StatefulWidget {
  static const routeName = 'group-registration';

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

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

class _GroupRegistrationState extends State<GroupRegistration> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final TextEditingController name = TextEditingController();
  final TextEditingController description = TextEditingController();

  int? id;
  late int clubId;

  late Club _selectedItem;

  final DatabaseService database = getIt<DatabaseService>();

  Future<List<dynamic>> doubleFuture() async {
    final args = ModalRoute.of(context)!.settings.arguments
        as GroupRegistrationArguments;

    final List<dynamic> returnList = [];

    final ClubDao clubDao = database.clubDao;
    final List<Club> clubList = await clubDao.findAllClubs();
    returnList.add(clubList);

    final GroupDao groupDao = database.groupDao;
    final Group? group = await groupDao.findGroupById(args.id);
    returnList.add(group);

    //await Future.delayed(const Duration(seconds: 1));

    return returnList;
  }

  final _title = 'Group Registration';

  final EdgeInsetsGeometry _defaultEdgeInsets =
      const EdgeInsets.symmetric(horizontal: 0.0, vertical: 16.0);

  // late Future<List<dynamic>> _double;

  // @override
  // void initState() {
  //   _double = doubleFuture();
  //   super.initState();
  // }

  @override
  void dispose() {
    name.dispose();
    description.dispose();
    super.dispose();
  }

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

    return FutureBuilder<List<dynamic>>(
        future: doubleFuture(),
        builder: (BuildContext context, AsyncSnapshot<List<dynamic>> snapshot) {
          if (!snapshot.hasData) {
            return const Text('Loading');
          }

          if (snapshot.hasData) {
            final List<Club> clubList = snapshot.data![0] as List<Club>;
            final Group group = snapshot.data! as Group;
            id = group.id;
            name.text = group.name;
            description.text = group.description;
            clubId = group.clubId;

            const Text(
              'Select a club to register your group with',
              style: TextStyle(fontWeight: FontWeight.bold),
            );

            DropdownButton<Club>(
              icon: const Icon(Icons.keyboard_arrow_down),
              items: clubList.map<DropdownMenuItem<Club>>((items) {
                return DropdownMenuItem<Club>(
                  child: Text(items.name),
                );
              }).toList(),
              onChanged: (Club? value) {
                setState(() {
                  _selectedItem = value!;
                  clubId = _selectedItem.id as int;
                });
              },
            );
          }
          return PlatformScaffold(
              appBar: PlatformAppBar(
                title: Text(_title),
              ),
              body: Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      CustomTextField(
                          labelText: 'Group Name',
                          hintText: 'Enter Group Name',
                          controller: name),
                      CustomTextField(
                          labelText: 'Description',
                          hintText: 'Enter Group Description',
                          controller: description),
                      Padding(
                          padding: _defaultEdgeInsets,
                          child: PlatformTextButton(
                              onPressed: () async {
                                await Future.delayed(
                                    const Duration(milliseconds: 300));
                                if (_formKey.currentState!.validate()) {
                                  if (id == null) {
                                    final Group group = Group(null, name.text,
                                        description.text, clubId);
                                    await dao.insertGroup(group);
                                  } else {
                                    final Group group = Group(null, name.text,
                                        description.text, clubId);
                                    await dao.updateGroup(group);
                                  }

                                  ScaffoldMessenger.of(context).showSnackBar(
                                      const SnackBar(
                                          content: Text('Processing Data')));

                                  Navigator.popUntil(context,
                                      ModalRoute.withName(GroupList.routeName));
                                }
                              },
                              child: const Text('Submit')))
                    ],
                  )));
        });
  }
}
