import 'dart:async';

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:wakelock/wakelock.dart';

class KriyaPage extends StatefulWidget {
  const KriyaPage({super.key});

  @override
  State<KriyaPage> createState() => _KriyaPageState();
}

class _KriyaPageState extends State<KriyaPage> {
  Duration kriyaDuration = const Duration(minutes: 1);
  Duration shavasanaDuration = const Duration(minutes: 7);
  late int exNumber = 38;
  late int totalDuration =
      kriyaDuration.inSeconds * exNumber + shavasanaDuration.inSeconds;

  late Timer _timer;
  late String startText = 'Старт';
  final player = AudioPlayer();

  bool isStarted() {
    if (totalDuration ==
        kriyaDuration.inSeconds * exNumber + shavasanaDuration.inSeconds) {
      return false;
    }
    return true;
  }

  void startTimer() {
    Wakelock.enable();
    if (startText == 'Пауза') {
      setState(() {
        player.dispose();
        startText = 'Возобновить';
        _timer.cancel();
      });
    } else {
      startText = 'Пауза';
      const oneSec = Duration(seconds: 1);
      _timer = Timer.periodic(
        oneSec,
        (Timer timer) {
          if (totalDuration == 0) {
            player.play(AssetSource('audio/finish.mp3'));
            stopTimer();
          } else if (totalDuration == shavasanaDuration.inSeconds) {
            player.play(AssetSource('audio/relax.mp3'));
            setState(() {
              totalDuration--;
            });
          } else if ((totalDuration - shavasanaDuration.inSeconds) %
                      kriyaDuration.inSeconds ==
                  0 &&
              (totalDuration - shavasanaDuration.inSeconds) > 0) {
            player.play(AssetSource('audio/start.mp3'));
            setState(() {
              totalDuration--;
            });
          } else {
            setState(() {
              totalDuration--;
            });
          }
        },
      );
    }
  }

  void stopTimer() {
    setState(() {
      Wakelock.disable();
      player.dispose();
      _timer.cancel();
      startText = 'Старт';
      totalDuration =
          kriyaDuration.inSeconds * exNumber + shavasanaDuration.inSeconds;
    });
  }

  void setRadio(value) {
    setState(() {
      exNumber = value!;
      totalDuration =
          kriyaDuration.inSeconds * exNumber + shavasanaDuration.inSeconds;
    });
  }

  void _showDialog(Widget child) {
    showCupertinoModalPopup<void>(
        context: context,
        builder: (BuildContext context) => Container(
              height: 216,
              padding: const EdgeInsets.only(top: 6.0),
              margin: EdgeInsets.only(
                bottom: MediaQuery.of(context).viewInsets.bottom,
              ),
              color: CupertinoColors.systemBackground.resolveFrom(context),
              child: SafeArea(
                top: false,
                child: child,
              ),
            ));
  }

  format(Duration duration) {
    final splitDuration = duration.toString().split(":");
    final hours = splitDuration[0];
    final minutes = splitDuration[1];
    final seconds = splitDuration[2].split('.')[0];
    return [hours, minutes, seconds];
  }

  @override
  void dispose() {
    _timer.cancel();
    player.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Крия йога'),
        ),
        body: ListView(
          padding: const EdgeInsets.all(16.0),
          children: [
            const Center(
                child: Text(
              "Какие крийи вы будете выполнять?",
              style: TextStyle(fontSize: 22.0),
            )),
            const Divider(),
            RadioListTile(
                title: const Text("Входные + круг 1 + круг 2"),
                value: 38,
                groupValue: exNumber,
                onChanged: isStarted() ? null : (value) => setRadio(value)),
            RadioListTile(
                title: const Text("Входные + круг 1"),
                value: 22,
                groupValue: exNumber,
                onChanged: isStarted() ? null : (value) => setRadio(value)),
            const Divider(),
            const Center(
                child: Text(
              "Продолжительность каждой крийи",
              style: TextStyle(fontSize: 22.0),
            )),
            CupertinoButton(
              onPressed: isStarted()
                  ? null
                  : () => _showDialog(
                        CupertinoTimerPicker(
                          mode: CupertinoTimerPickerMode.ms,
                          initialTimerDuration: kriyaDuration,
                          onTimerDurationChanged: (Duration newDuration) {
                            setState(() {
                              kriyaDuration = newDuration;
                              totalDuration =
                                  kriyaDuration.inSeconds * exNumber +
                                      shavasanaDuration.inSeconds;
                            });
                          },
                        ),
                      ),
              child: Text(
                format(kriyaDuration)[1] + ":" + format(kriyaDuration)[2],
                style: const TextStyle(
                  fontSize: 22.0,
                ),
              ),
            ),
            const Divider(),
            const Center(
                child: Text(
              "Продолжительность силовых крий + шавасаны",
              style: TextStyle(fontSize: 22.0),
            )),
            CupertinoButton(
              onPressed: isStarted()
                  ? null
                  : () => _showDialog(
                        CupertinoTimerPicker(
                          mode: CupertinoTimerPickerMode.ms,
                          initialTimerDuration: shavasanaDuration,
                          onTimerDurationChanged: (Duration newDuration) {
                            setState(() {
                              shavasanaDuration = newDuration;
                              totalDuration =
                                  kriyaDuration.inSeconds * exNumber +
                                      shavasanaDuration.inSeconds;
                            });
                          },
                        ),
                      ),
              child: Text(
                format(shavasanaDuration)[1] +
                    ":" +
                    format(shavasanaDuration)[2],
                style: const TextStyle(
                  fontSize: 22.0,
                ),
              ),
            ),
            const Divider(),
            Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  ElevatedButton(
                      onPressed: () => startTimer(), child: Text(startText)),
                  const SizedBox(width: 50),
                  ElevatedButton(
                      onPressed: isStarted() ? () => stopTimer() : null,
                      child: const Text('Стоп'))
                ]),
            const Divider(),
            const Center(
                child: Text(
              "Осталось практиковать:",
              style: TextStyle(fontSize: 22.0),
            )),
            const Divider(),
            Center(
                child: Text(
                    "${format(Duration(seconds: totalDuration)).join(':')}",
                    style: const TextStyle(fontSize: 22.0)))
          ],
        ));
  }
}
