import 'package:flutter/material.dart';
import 'package:skillcourt/pages/play_setup/game_length.dart';
import 'package:skillcourt/pages/play_setup/game_repeats.dart';
import 'package:skillcourt/pages/play_setup/pad_light_delay.dart';
import 'package:skillcourt/pages/play_setup/pad_light_up.dart';
import 'package:skillcourt/pages/play_setup/play_setup_item.dart';
import 'package:skillcourt/pages/play_setup/saved_games.dart';
import 'package:skillcourt/widgets/custom_button.dart';

class PlaySetUp extends StatefulWidget {
  static const routeName = 'PlaySetUp';
  static PlaySetUpItem playSetUpItem = PlaySetUpItem(null,
      padLightUp: null,
      padLightDelay: null,
      gameRepeats: null,
      gameLength: null,
      padSequence: 'Custom');

  const PlaySetUp({super.key});

  @override
  State<PlaySetUp> createState() => _PlaySetUpState();
}

enum GamePlay { New, Saved }

class _PlaySetUpState extends State<PlaySetUp> {
  GamePlay gamePlayView = GamePlay.New;
  int _blackPrimaryValue = 0xFF000000;
  int currentPage = 0;

  late int? gameRepeatsIndex;

  bool byHits = false;
  bool saved = false;

  @override
  void initState() {
    super.initState();
    gameRepeatsIndex = null;
  }

  Widget topIcon() {
    if (!saved) {
      return Header(
          onPressed: () {
            //CHECK THAT ALL FIELDS ARE FILLED
            if (PlaySetUp.playSetUpItem.validateSetUp()) {
              Navigator.of(context)
                  .pushNamed('SaveGame', arguments: PlaySetUp.playSetUpItem);
            } else {
              const snackBar = SnackBar(
                content: Text('Please finish your play set up'),
              );
              ScaffoldMessenger.of(context).showSnackBar(snackBar);
            }
          },
          icon: (Icons.save_outlined));
    } else {
      return Header(
          onPressed: () {
            showModalBottomSheet<void>(
              context: context,
              builder: (BuildContext context) {
                return SizedBox(
                  height: 200,
                  child: Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        const Text('Modal BottomSheet'),
                        ElevatedButton(
                          child: const Text('Close BottomSheet'),
                          onPressed: () => Navigator.pop(context),
                        ),
                      ],
                    ),
                  ),
                );
              },
            );
          },
          icon: (Icons.delete_outline));
    }
  }

  @override
  Widget build(BuildContext context) {
    final List<Widget> options = [
      mainMenu(),
      pad_light_up_menu(),
      padLightDelayWidget(),
      gameRepeatsWidget(),
      const Text('XD'),
      gameLengthWidget(),
      savedGames()
    ];
    Widget body() {
      switch (currentPage) {
        case 0:
          return options[currentPage];
        case 1:
          return options[currentPage];
        case 2:
          return options[currentPage];
        case 3:
          return options[currentPage];
        case 5:
          return options[currentPage];
        case 6:
          return options[currentPage];
      }
      return mainMenu();
    }

    return Theme(
        data: ThemeData(
            primarySwatch: MaterialColor(
              _blackPrimaryValue,
              <int, Color>{
                50: const Color(0xFF000000),
                100: const Color(0xFF000000),
                200: const Color(0xFF000000),
                300: const Color(0xFF000000),
                400: const Color(0xFF000000),
                500: Color(_blackPrimaryValue),
                600: const Color(0xFF000000),
                700: const Color(0xFF000000),
                800: const Color(0xFF000000),
                900: const Color(0xFF000000),
              },
            ),
            cardTheme: const CardTheme(elevation: 0)),
        child: Scaffold(
          appBar: null,
          body: SafeArea(
            child: Padding(padding: const EdgeInsets.all(8.0), child: body()),
          ),
        ));
  }

  Widget mainMenu() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        header(),
        Expanded(
          child: !saved
              ? ListView(
                  children: [
                    const Padding(
                      padding: EdgeInsets.all(8.0),
                      child: Text("Let's set up your perfect game!"),
                    ),
                    PlaySettingButton(
                      title: 'Pad light up',
                      icon: Icons.wb_sunny_outlined,
                      onTap: () {
                        setState(() {
                          currentPage = 1;
                        });
                      },
                      selection: PlaySetUp.playSetUpItem.padLightUp,
                      unit: 'Sec',
                    ),
                    PlaySettingButton(
                      title: 'Pad light delay',
                      icon: Icons.access_alarm,
                      onTap: () {
                        setState(() {
                          currentPage = 2;
                        });
                      },
                      selection: PlaySetUp.playSetUpItem.padLightDelay,
                      unit: 'Sec',
                    ),
                    PlaySettingButton(
                      title: 'Game repeats',
                      icon: Icons.compare_arrows,
                      onTap: () {
                        setState(() {
                          currentPage = 3;
                        });
                      },
                      selection: PlaySetUp.playSetUpItem.gameRepeats,
                      unit: '',
                    ),
                    PlaySettingButton(
                      title: 'Pad sequence',
                      icon: Icons.border_all,
                      selection: PlaySetUp.playSetUpItem.padSequence,
                      unit: '',
                    ),
                    GameLengthSettingButton(
                      title: 'Game length',
                      icon: Icons.timer_sharp,
                      function: () {
                        setState(() {
                          currentPage = 5;
                        });
                      },
                      selection: (PlaySetUp.playSetUpItem.gameLength != false &&
                              !((PlaySetUp.playSetUpItem.minutes == 0 &&
                                      PlaySetUp.playSetUpItem.seconds == 0) ||
                                  PlaySetUp.playSetUpItem.numOfHits == 0))
                          ? PlaySetUp.playSetUpItem.gameLength
                          : null,
                    ),
                  ],
                )
              : savedGames(),
        ),
        currentPage == 0
            ? Padding(
                padding: const EdgeInsets.all(8.0),
                child: CustomButton(
                    label: 'Start Game',
                    onPressed: () {
                      PlaySetUp.playSetUpItem.padSequence = 'Custom';
                      if (PlaySetUp.playSetUpItem.validateSetUp()) {
                        Navigator.pushNamed(context, 'PlayTimerPage',
                            arguments: PlaySetUp.playSetUpItem);
                      }
                    }),
              )
            : const SizedBox(
                height: 20,
              ),
        Padding(
          padding: const EdgeInsets.all(10.0),
          child: CustomButton(
            label: 'Close',
            onPressed: () {
              if (currentPage == 0 || currentPage == 6) {
                Navigator.pop(context);
              } else {
                setState(() {
                  currentPage = 0;
                });
              }
            },
            isWhite: true,
          ),
        ),
      ],
    );
  }

  Widget pad_light_up_menu() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.max,
      children: [
        PadLightUp(
          currentSelection: PlaySetUp.playSetUpItem.padLightUp,
          secondSelected: (index) {
            setState(() {
              if (index == 0) {
                PlaySetUp.playSetUpItem.padLightUp = null;
              } else {
                PlaySetUp.playSetUpItem.padLightUp = index;
              }
            });
          },
          onTap: PlaySetUp.playSetUpItem.padLightUp != null
              ? () {
                  setState(() {
                    currentPage = 0;
                  });
                }
              : null,
        ),
        Expanded(
          child: Align(
              alignment: Alignment.bottomCenter,
              child: CustomButton(
                  label: 'Close',
                  onPressed: () {
                    setState(() {
                      currentPage = 0;
                    });
                  },
                  isWhite: true)),
        ),
      ],
    );
  }

  Widget padLightDelayWidget() {
    return Column(
      mainAxisSize: MainAxisSize.max,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        PadLightDelay(
          currentSelection: PlaySetUp.playSetUpItem.padLightDelay,
          secondSelected: (index) {
            setState(() {
              if (index == 0) {
                PlaySetUp.playSetUpItem.padLightDelay = null;
              } else {
                PlaySetUp.playSetUpItem.padLightDelay = index;
              }
            });
          },
          onTap: PlaySetUp.playSetUpItem.padLightDelay != null
              ? () {
                  setState(() {
                    currentPage = 0;
                  });
                }
              : null,
        ),
        Expanded(
          child: Align(
              alignment: Alignment.bottomCenter,
              child: CustomButton(
                  label: 'Close',
                  onPressed: () {
                    setState(() {
                      currentPage = 0;
                    });
                  },
                  isWhite: true)),
        ),
      ],
    );
  }

  Widget gameRepeatsWidget() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        GameRepeats(
          currentSelection: gameRepeatsIndex,
          repeatsSelected: (index) {
            setState(() {
              gameRepeatsIndex = index;
              final int val = index + 2;
              if (val != 11) {
                PlaySetUp.playSetUpItem.gameRepeats = '$val x';
              } else {
                PlaySetUp.playSetUpItem.gameRepeats = 'No';
              }
            });
          },
          onTap: PlaySetUp.playSetUpItem.gameRepeats != null
              ? () {
                  setState(() {
                    currentPage = 0;
                  });
                }
              : null,
        ),
        Expanded(
          child: Align(
              alignment: Alignment.bottomCenter,
              child: CustomButton(
                  label: 'Close',
                  onPressed: () {
                    setState(() {
                      currentPage = 0;
                    });
                  },
                  isWhite: true)),
        ),
      ],
    );
  }

  Widget gameLengthWidget() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Expanded(
          child: ListView(
            children: [
              GameLength(
                currentMinutes: PlaySetUp.playSetUpItem.minutes,
                currentSeconds: PlaySetUp.playSetUpItem.seconds,
                currentHits: PlaySetUp.playSetUpItem.numOfHits,
                byHits: byHits,
                hitsSwitch: (value) {
                  setState(() {
                    byHits = value!;
                  });
                },
                minutesSelected: (index) {
                  setState(() {
                    PlaySetUp.playSetUpItem.minutes = index;
                    PlaySetUp.playSetUpItem.numOfHits = null;
                    if (PlaySetUp.playSetUpItem.seconds == null)
                      PlaySetUp.playSetUpItem.seconds = 0;
                    PlaySetUp.playSetUpItem.gameLength =
                        '${PlaySetUp.playSetUpItem.minutes} Mins ${PlaySetUp.playSetUpItem.seconds} Secs';
                  });
                },
                secondsSelected: (index) {
                  setState(() {
                    PlaySetUp.playSetUpItem.seconds = index;
                    PlaySetUp.playSetUpItem.numOfHits = null;
                    if (PlaySetUp.playSetUpItem.minutes == null)
                      PlaySetUp.playSetUpItem.minutes = 0;
                    PlaySetUp.playSetUpItem.gameLength =
                        '${PlaySetUp.playSetUpItem.minutes} Mins ${PlaySetUp.playSetUpItem.seconds} Secs';
                  });
                },
                numOfHitsSelected: (index) {
                  setState(() {
                    PlaySetUp.playSetUpItem.minutes = null;
                    PlaySetUp.playSetUpItem.seconds = null;
                    PlaySetUp.playSetUpItem.numOfHits = index;
                    // if (padHitsGameLength != null)
                    PlaySetUp.playSetUpItem.gameLength =
                        '${PlaySetUp.playSetUpItem.numOfHits} hits';
                  });
                },
                onTap: PlaySetUp.playSetUpItem.gameLength != null
                    ? () {
                        setState(() {
                          currentPage = 0;
                        });
                      }
                    : null,
              ),
            ],
          ),
        ),
        Align(
            alignment: Alignment.bottomCenter,
            child: CustomButton(
                label: 'Close',
                onPressed: () {
                  setState(() {
                    currentPage = 0;
                  });
                },
                isWhite: true)),
      ],
    );
  }

  Widget savedGames() {
    return SavedGames();
  }

  Widget header() {
    final double width = MediaQuery.of(context).size.width;
    return Column(children: [
      Row(
        children: [
          Expanded(
            child: topIcon(),
          )
        ],
      ),
      SizedBox(
        width: width,
        child: SegmentedButton(
          showSelectedIcon: false,
          segments: const [
            ButtonSegment<GamePlay>(
              value: GamePlay.New,
              label: Text('New'),
            ),
            ButtonSegment<GamePlay>(
              value: GamePlay.Saved,
              label: Text('Saved'),
            ),
          ],
          selected: <GamePlay>{gamePlayView},
          onSelectionChanged: (Set<GamePlay> newSelection) {
            setState(() {
              gamePlayView = newSelection.first;
              if (gamePlayView == GamePlay.Saved) {
                saved = true;
              } else {
                saved = false;
                currentPage = 0;
              }
            });
          },
        ),
      ),
    ]);
  }
}

class PlaySettingButton extends StatelessWidget {
  const PlaySettingButton(
      {super.key,
      required this.title,
      required this.icon,
      this.onTap,
      this.selection,
      this.unit});

  final String title;
  final IconData icon;
  final Function()? onTap;
  final dynamic selection;
  final String? unit;

  @override
  Widget build(BuildContext context) {
    bool contentFilled = selection != null && unit != null;
    return InkWell(
      onTap: onTap,
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Container(
          height: 65.0,
          decoration: BoxDecoration(
            color: const Color(0xFFDEDEDE),
            borderRadius: BorderRadius.circular(8.0),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  const SizedBox(
                    width: 10,
                  ),
                  // SvgPicture.asset(assetName),
                  Icon(icon),
                  Padding(
                    padding: const EdgeInsets.only(left: 16.0),
                    child: Text(
                      title,
                      semanticsLabel: title,
                      style: const TextStyle(
                        fontFamily: 'Product Sans',
                        fontSize: 24.0,
                        color: Color(0xFF323438),
                      ),
                    ),
                  ),
                ],
              ),
              Card(
                elevation: 0,
                color: const Color(0xFFD9D128),
                child: SizedBox(
                  width: contentFilled ? 90 : 10,
                  height: 65,
                  child: Center(
                      child: Text(
                    contentFilled ? '$selection $unit' : '',
                    style: const TextStyle(
                        fontWeight: FontWeight.bold, fontSize: 20),
                  )),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

class Header extends StatelessWidget {
  const Header({super.key, this.onPressed, required this.icon});

  final Function()? onPressed;
  final IconData icon;

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        const Text(
          'Play Set Up',
          style: TextStyle(
            fontFamily: 'Product Sans',
            fontWeight: FontWeight.w900,
            fontSize: 46.0,
            color: Color(0xFF323438),
          ),
        ),
        IconButton(onPressed: onPressed, icon: Icon(icon))
      ],
    );
  }
}
