import 'package:flutter/material.dart';
import 'package:skillcourt/pages/home_new.dart';
import 'package:skillcourt/pages/play_setup/play_setup_item.dart';
import 'package:skillcourt/pages/play_setup/save_game/db_helper.dart';
import 'package:skillcourt/widgets/custom_appbar.dart';
import 'package:skillcourt/widgets/custom_button.dart';
import 'package:skillcourt/widgets/text_field.dart';

class SaveGame extends StatefulWidget {
  const SaveGame({
    super.key,
    required this.playSetUpItem,
  });

  final PlaySetUpItem playSetUpItem;
  static const routeName = 'SaveGame';

  @override
  State<SaveGame> createState() => _SaveGameState();
}

class _SaveGameState extends State<SaveGame> {
  late TextEditingController sessionNameController;
  late PlaySetUpItem playSetUpItem;

  // DBHelper dbHelper = new DBHelper();
  Future<int> setSessionID() async {
    int count = await getIt<DBHelper>().getCountPlaySetUps();
    return count + 1;
  }

  @override
  void initState() {
    super.initState();

    ///TODO: dynamically change number of session based on how many there are in the database
    ///Get count from database
    setSessionID();
    sessionNameController = TextEditingController();
    playSetUpItem = widget.playSetUpItem;
  }

  @override
  void dispose() {
    super.dispose();
    sessionNameController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: const CustomAppBar(
        title: 'Save game?',
      ),
      body: FutureBuilder<int>(
          future: setSessionID(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              // While waiting for data, display a loading screen
              return CircularProgressIndicator(); // Replace with your loading widget
            } else if (snapshot.hasError) {
              // Handle errors if needed
              return Text('Error: ${snapshot.error}');
            } else {
              // Data is available, show the actual app
              int sessionID =
                  snapshot.data ?? 0; // Use the data or a default value
              playSetUpItem.id = sessionID;
              sessionNameController.text = 'Session $sessionID';
              print(sessionID);
              return Padding(
                padding: const EdgeInsets.all(20.0),
                child: Column(
                  children: [
                    CustomTextField(
                      labelText: 'Name',
                      hintText: 'Set up name',
                      controller: sessionNameController,
                    ),
                    playSetUpItem.gameSessionDisplay(),
                    Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: CustomButton(
                          label: 'Save',
                          onPressed: () async {
                            setState(() {
                              playSetUpItem.name = sessionNameController.text;
                            });
                            if (playSetUpItem.name != null) {
                              await getIt<DBHelper>()
                                  .addPlaySetUp(playSetUpItem);

                              Navigator.pop(context);
                            } else {
                              const snackBar = SnackBar(
                                content: Text('Please name your session'),
                              );
                              ScaffoldMessenger.of(context)
                                  .showSnackBar(snackBar);
                            }
                          }),
                    ),
                    CustomButton(
                      label: 'Close',
                      onPressed: () {
                        Navigator.pop(context);
                      },
                      isWhite: true,
                    ),
                  ],
                ),
              );
            }
          }),
    );
  }
}
