import 'package:circular_countdown_timer/circular_countdown_timer.dart';
import 'package:flutter/material.dart';
import 'package:skillcourt/pages/play_setup/play_setup_item.dart';

import 'package:skillcourt/widgets/custom_appbar.dart';
import 'package:skillcourt/widgets/custom_button.dart';

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

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

  @override
  State<PlayTimerPage> createState() => _PlayTimerPageState();
}

class _PlayTimerPageState extends State<PlayTimerPage> {
  late int _duration;
  final CountDownController _controller = CountDownController();
  bool running = false;

  Widget playPauseButton() {
    if (running) {
      return _button(
        semanticLabel: 'Pause',
        icon: Icons.pause,
        onPressed: () {
          setState(() {
            running = !running;
          });
          _controller.pause();
        },
      );
    } else {
      return _button(
        semanticLabel: 'Play',
        onPressed: () {
          setState(() {
            running = !running;
          });
          _controller.resume();
        },
        icon: Icons.play_arrow,
      );
    }
  }

  @override
  void initState() {
    _duration = Duration(
            minutes: widget.playSetUpItem.minutes!,
            seconds: widget.playSetUpItem.seconds!)
        .inSeconds;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        title: 'Game on!',
      ),
      body: Column(
        children: [
          Stack(
            alignment: Alignment.center,
            //TODO: FIX POSITION OF ICON
            children: [
              Column(
                children: [
                  Icon(Icons.timer_sharp),
                  SizedBox(
                    height: 70,
                  )
                ],
              ),
              CircularCountDownTimer(
                isReverse: true,
                //Shows time count down in Minute and seconds
                textFormat: CountdownTextFormat.MM_SS,
                // Countdown duration in Seconds.
                duration: _duration,

                // Countdown initial elapsed Duration in Seconds.
                initialDuration: 0,

                // Controls (i.e Start, Pause, Resume, Restart) the Countdown Timer.
                controller: _controller,

                // Width of the Countdown Widget.
                width: MediaQuery.of(context).size.width / 2,

                // Height of the Countdown Widget.
                height: MediaQuery.of(context).size.height / 2,

                // Ring Color for Countdown Widget.
                ringColor: Colors.grey[300]!,

                // Filling Color for Countdown Widget.
                fillColor: Color(0xFFD9D128),

                // Border Thickness of the Countdown Ring.
                strokeWidth: 20.0,

                // Text Style for Countdown Text.
                textStyle: const TextStyle(
                  fontSize: 33.0,
                  color: Colors.black,
                  fontWeight: FontWeight.bold,
                ),

                // Handles visibility of the Countdown Text.
                isTimerTextShown: true,

                // Handles the timer start.
                autoStart: false,

                // This Callback will execute when the Countdown Starts.
                onStart: () {
                  // Here, do whatever you want
                  debugPrint('Countdown Started');
                },

                // This Callback will execute when the Countdown Ends.
                onComplete: () {
                  // Here, do whatever you want
                  debugPrint('Countdown Ended');
                },

                // This Callback will execute when the Countdown Changes.
                onChange: (String timeStamp) {
                  // Here, do whatever you want
                  debugPrint('Countdown Changed $timeStamp');
                },

                /*
                * Function to format the text.
                * Allows you to format the current duration to any String.
                * It also provides the default function in case you want to format specific moments
                  as in reverse when reaching '0' show 'GO', and for the rest of the instances follow
                  the default behavior.
              */
                timeFormatterFunction: (defaultFormatterFunction, duration) {
                  int _minutes = widget.playSetUpItem.minutes!;
                  int _seconds = widget.playSetUpItem.seconds!;
                  String _min = _minutes < 10 ? '0$_minutes' : '$_minutes';
                  String _sec = _seconds < 10 ? '0$_seconds' : '$_minutes';

                  // if (duration.inSeconds == 0) {
                  //   // only format for '0'
                  //   return '$_min:$_sec';
                  // } else {
                  // other durations by it's default format
                  return Function.apply(defaultFormatterFunction, [duration]);

                  // }
                },
              ),
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              playPauseButton(),
              _button(
                semanticLabel: 'Restart',
                onPressed: () => _controller.restart(duration: _duration),
                icon: Icons.restart_alt_outlined,
              ),
            ],
          ),
          Divider(),
          Text('SHOW Remaining hits'),
          Divider(),
          CustomButton(label: 'Done', onPressed: () {})
        ],
      ),
    );
  }
}

Widget _button(
    {required String semanticLabel,
    required IconData icon,
    VoidCallback? onPressed}) {
  return SizedBox(
    width: 70,
    height: 70,
    child: ElevatedButton(
      style: ElevatedButton.styleFrom(
          elevation: 0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(70),
          ),
          backgroundColor: Colors.white,
          foregroundColor: Colors.black),
      onPressed: onPressed,
      child: Icon(
        icon,
        semanticLabel: semanticLabel,
      ),
    ),
  );
}
