import 'package:daily_challenge/daily_challenge.dart';
import 'package:daily_challenge/ui/pages/calendar/challenge_calendar_page.dart';
import 'package:daily_challenge/ui/pages/congratulations/congratulations_page.dart';
import 'package:flutter/animation.dart';
import 'package:flutter/material.dart';
import 'package:guru_utils/router/router.dart';
import 'package:get/get.dart' hide Rx;
import 'package:guru_popup/guru_popup.dart';

/// Created by Haoyi on 2023/10/9

class DelayedTransitionTween extends Tween<Offset> {
  DelayedTransitionTween({Offset? begin, Offset? end, this.delay = 0.0})
      : super(begin: begin, end: end);

  final double delay;

  @override
  Offset lerp(double t) {
    if (t < delay) {
      return begin!;
    }
    return super.lerp((t - delay) / (1 - delay));
  }
}

class FadeTween extends Tween<double> {
  final double limit;

  FadeTween(this.limit)
      : super(
          begin: 0.0,
          end: 1.0,
        );

  @override
  double lerp(double t) {
    if (t > limit) {
      return end!;
    }
    return super.lerp(1 - (limit - t) / limit);
  }
}

class DailyChallengeRoutes {
  static const dailyChallenge = RoutePath("daily_challenge");

  static final dailyChallengePage = GetPage(
      preventDuplicates: true,
      name: dailyChallenge.mainPath,
      page: () => ChallengeCalendarPage(),
      transition: Transition.fadeIn,
      bindings: [
        DailyChallengeBinding(),
      ],
      title: null);
}

extension DailyChallengeRouteCenter on RouteCenter {
  Future openDailyChallenge() async {
    openPath(DailyChallengeRoutes.dailyChallenge.path());
  }
}

extension DailyChallengePopup on GuruPopup {
  static Widget _buildCongratsTransitions(
      BuildContext context,
      Animation<double> animation,
      Animation<double> secondaryAnimation,
      Widget child) {
    return SlideTransition(
      position: DelayedTransitionTween(
              begin: const Offset(0.0, 1.0),
              end: const Offset(0.0, 0.0),
              delay: 0.22330097)
          .animate(animation),
      child: FadeTransition(
          opacity: FadeTween(0.38834951).animate(animation), child: child),
    );
  }

  Future showDailyChallengeCongrats(DateTime focusDate) async {
    DailyChallengeManager.instance.config.callbacks
        ?.onCongratulationsPageImpression(focusDate);
    await GuruPopup.instance.showDialog(
        widget: CongratulationPage(yearMonth: focusDate),
        useSafeArea: false,
        transition: DailyChallengePopup._buildCongratsTransitions,
        transitionDuration: const Duration(milliseconds: 400));
  }
}
