import 'package:flutter/material.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';
import 'package:flutter_platform_widgets/flutter_platform_widgets.dart';
import 'package:get_it/get_it.dart';
import 'package:intl_phone_number_input/intl_phone_number_input.dart';
import 'package:skillcourt/dao/player_dao.dart';
import 'package:skillcourt/entity/player.dart';
import 'package:skillcourt/services/database.dart';
import 'package:skillcourt/widgets/text_field.dart';

final getIt = GetIt.instance;

class PlayerRegistrationArguments {
  final int id;

  PlayerRegistrationArguments(this.id);
}

class PlayerRegistration extends StatefulWidget {
  static const routeName = 'player-registration';

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

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

class _PlayerRegistrationState extends State<PlayerRegistration> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final TextEditingController firstName = TextEditingController();
  final TextEditingController lastName = TextEditingController();
  final TextEditingController email = TextEditingController();
  final TextEditingController birthdate = TextEditingController();
  final TextEditingController phoneNumber = TextEditingController();

  PhoneNumber number = PhoneNumber(isoCode: 'US');
  Color hitColor = Colors.red;

  int? id;

  final DatabaseService database = getIt<DatabaseService>();

  final _title = 'Player Registration';

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

  @override
  void dispose() {
    firstName.dispose();
    lastName.dispose();
    email.dispose();
    birthdate.dispose();
    phoneNumber.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final PlayerDao dao = database.playerDao;
    final args = ModalRoute.of(context)!.settings.arguments
        as PlayerRegistrationArguments;

    return FutureBuilder<Player?>(
        future: dao.findPlayerById(args.id),
        builder: (BuildContext context, AsyncSnapshot<Player?> snapshot) {
          if (snapshot.hasData) {
            final Player player = snapshot.data as Player;
            id = player.id;
            firstName.text = player.firstName;
            lastName.text = player.lastName;
            email.text = player.email;
            birthdate.text = player.birthday.toString();
            phoneNumber.text = player.phoneNumber;
            number =
                PhoneNumber(phoneNumber: player.phoneNumber, isoCode: 'US');
            hitColor = Color(int.parse(player.hitColor)).withOpacity(1);
          }

          return PlatformScaffold(
              appBar: PlatformAppBar(
                title: Text(_title),
              ),
              body: Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      CustomTextField(
                          labelText: 'First Name',
                          hintText: 'Enter First Name',
                          controller: firstName),
                      CustomTextField(
                          labelText: 'Last Name',
                          hintText: 'Enter Last Name',
                          controller: lastName),
                      CustomTextField(
                          labelText: 'Date of Birth',
                          hintText: 'Enter Date of Birth',
                          controller: birthdate,
                          onTap: () async {
                            FocusScope.of(context).requestFocus(FocusNode());

                            final date = await showDatePicker(
                                context: context,
                                initialDate: DateTime.now(),
                                firstDate: DateTime(1900),
                                lastDate: DateTime.now());
                            if (date != null) {
                              birthdate.text = date.toLocal().toString();
                            }
                          }),
                      Padding(
                          padding: _defaultEdgeInsets,
                          child: InternationalPhoneNumberInput(
                              onInputChanged: (PhoneNumber number) {
                                setState(() {
                                  this.number = number;
                                });
                              },
                              hintText: 'Enter your phone number',
                              textFieldController: phoneNumber,
                              initialValue: number)),
                      Padding(
                        padding: _defaultEdgeInsets,
                        child: PlatformElevatedButton(
                            onPressed: () {
                              showDialog(
                                  context: context,
                                  builder: (BuildContext context) {
                                    return AlertDialog(
                                        title: const Text('Select a color'),
                                        content: SingleChildScrollView(
                                            child: BlockPicker(
                                                pickerColor: hitColor,
                                                onColorChanged: (Color color) {
                                                  setState(() {
                                                    hitColor = color;
                                                  });
                                                })));
                                  });
                            },
                            child: const Text('Pad Hit Color')),
                      ),
                      Padding(
                          padding: _defaultEdgeInsets,
                          child: PlatformElevatedButton(
                              onPressed: () async {
                                await Future.delayed(
                                    const Duration(milliseconds: 300));
                                if (_formKey.currentState!.validate()) {
                                  final birthday =
                                      DateTime.parse(birthdate.text);

                                  if (id == null) {
                                    final Player player = Player(
                                        null,
                                        firstName.text,
                                        lastName.text,
                                        birthday,
                                        email.text,
                                        phoneNumber.text,
                                        hitColor.value.toString());
                                    await dao.insertPlayer(player);
                                  } else {
                                    final Player player = Player(
                                        id,
                                        firstName.text,
                                        lastName.text,
                                        birthday,
                                        email.text,
                                        phoneNumber.text,
                                        hitColor.value.toString());
                                    await dao.updatePlayer(player);
                                  }

                                  if (!mounted) return;

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

                                  Navigator.pop(context);
                                }
                              },
                              child: const Text('Submit')))
                    ],
                  )));
        });
  }
}
