import 'dart:io';

import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';
import 'package:lottie/lottie.dart';

class SuccessDialog extends StatefulWidget {
  bool isFromDashboard;

  SuccessDialog(this.isFromDashboard);

  @override
  State<SuccessDialog> createState() => _SuccessDialogState();
}

class _SuccessDialogState extends State<SuccessDialog> with TickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    _controller = AnimationController(vsync: this);

    super.initState();
  }

  Future<void> playSuccessSound() async {
    AudioPlayer player = AudioPlayer();
    String audioAsset = "";
    if (Platform.isAndroid) {
      audioAsset = "assets/audio/success_tone_android.mp3";
    } else {
      audioAsset = "assets/audio/success_tone_ios.caf";
    }
    await player.setAsset(audioAsset);
    await player.load();
    player.play();
  }

  @override
  Widget build(BuildContext context) {
    double size = MediaQuery.of(context).size.width / 1.8;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          width: size,
          height: size,
          child: Card(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(25.0),
            ),
            child: Lottie.asset(
              'assets/lottie/lt_success.json',
              repeat: false,
              reverse: false,
              controller: _controller,
              frameRate: FrameRate(60.0),
              onLoaded: (LottieComposition v) async {
                await playSuccessSound();
                _controller
                  ..duration = v.duration
                  ..forward().whenComplete(() async {
                    Navigator.pop(context);
                    if (widget.isFromDashboard) Navigator.pop(context);
                  });
              },
            ),
          ),
        ),
      ],
    );
  }
}
