import 'dart:async';

import 'package:daily_challenge/daily_challenge.dart';
import 'package:daily_challenge/l10n/localizations/app_strings.dart';
import 'package:guru_widgets/guru_widgets.dart';
import 'package:guru_widgets/theme/guru_theme.dart';
import 'package:design/design.dart';
import 'package:guru_utils/datetime/datetime_utils.dart';
import 'package:guru_utils/log/log.dart';
import 'dart:ui' as ui show Image;
import 'package:intl/intl.dart';
import 'package:guru_utils/router/router.dart';

/// Created by Haoyi on 2023/10/12

part 'congratulations_page.g.dart';

@DesignSpec(width: 750, height: 1624, specMode: SpecMode.useGet)
abstract class CongratulationsPageDesignSpec implements BasicDesignSpec {
  @CombinedSpec(SpecStatusBarHeight(50), SpecVertical(188))
  double get titleTopSpacing;

  @SpecHeight(60)
  double get titleHeight;

  @SpecHeight(638)
  double get titleBottomSpacing;

  @SpecHeight(164)
  double get summaryRegionHeight;

  @SpecHeight(56)
  double get summaryBottomSpacing;

  @SpecHeight(104)
  double get buttonHeight;

  @SpecWidth(60)
  double get buttonHorizontalSpacing;

  @SpecHeight(126)
  double get buttonBottomSpacing;

  @SpecHeight(918)
  double get allWidgetsHeight;

  @SpecAbsoluteFontSize(48)
  double get titleFontSize;

  @SpecWidth(760)
  double get lottieRegionSize;

  @SpecWidth(440)
  double get exhibitRegionSize;

  @SpecEdgeInsets.symmetric(horizontal: SpecHorizontal(88))
  EdgeInsets get summaryPadding;

  @SpecAbsoluteFontSize(28)
  double get summaryFontSize;

  static CongratulationsPageDesignSpec get() {
    return _CongratulationsPageDesignSpec.get();
  }
}

class CongratulationTheme {
  final Color? summaryColor;
  final GuruButtonStyle? buttonStyle;
  final LottieAsset? animatedTrophyBackground;
  final BoxDecoration? decoration;

  static final CongratulationTheme defaultTheme = CongratulationTheme();

  CongratulationTheme(
      {this.summaryColor,
      this.buttonStyle,
      this.animatedTrophyBackground,
      this.decoration});
}

class CongratulationPage extends StatelessWidget {
  final DateTime yearMonth;
  static final DateFormat MMMMyFormat = DateFormat('MMMM y');

  const CongratulationPage({super.key, required this.yearMonth});

  Future<ui.Image> _loadImage(ImageProvider provider) async {
    final ImageStream stream = provider.resolve(const ImageConfiguration());
    final Completer<ui.Image> completer = Completer<ui.Image>();
    void listener(ImageInfo info, bool _) {
      if (!completer.isCompleted) {
        completer.complete(info.image);
      }
    }

    final ImageStreamListener imageStreamListener =
        ImageStreamListener(listener);
    stream.addListener(imageStreamListener);

    return await completer.future;
  }

  @override
  Widget build(BuildContext context) {
    final designSpec = CongratulationsPageDesignSpec.get();
    final appStrings = DailyChallengeStrings.of();
    final guruTheme = GuruTheme.of(context);
    final theme = guruTheme.getCustomTheme<CongratulationTheme>(
            CongratulationTheme.defaultTheme.runtimeType) ??
        CongratulationTheme.defaultTheme;
    final animatedTrophyBackground = theme.animatedTrophyBackground;

    final screenHeight = MediaQuery.of(context).size.height;
    final screenWidth = MediaQuery.of(context).size.width;

    final lottieHorizontal =
        (designSpec.measuredSize.width - designSpec.lottieRegionSize) / 2.0;

    double titleTopSpacing = designSpec.titleTopSpacing;
    double titleBottomSpacing = designSpec.titleBottomSpacing;
    double summaryBottomSpacing = designSpec.summaryBottomSpacing;
    double buttonBottomSpacing = designSpec.buttonBottomSpacing;

    final overHeight = screenHeight -
        designSpec.allWidgetsHeight -
        designSpec.buttonHeight -
        designSpec.titleTopSpacing -
        designSpec.buttonBottomSpacing;

    titleTopSpacing += (overHeight * 0.25);
    titleBottomSpacing += (overHeight * 0.44);
    summaryBottomSpacing += (overHeight * 0.1);
    buttonBottomSpacing += (overHeight * 0.16);

    double lottieTopSpacing =
        (titleBottomSpacing - designSpec.exhibitRegionSize) * 0.6218;
    lottieTopSpacing += designSpec.titleHeight;
    lottieTopSpacing += titleTopSpacing;
    lottieTopSpacing -=
        (designSpec.lottieRegionSize - designSpec.exhibitRegionSize) * 0.58;

    return DecoratedBox(
      decoration: theme.decoration ??
          const BoxDecoration(
              gradient: LinearGradient(
                  colors: [Color(0xFF026A3E), Color(0xFF013527)],
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter)),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: Stack(
          fit: StackFit.expand,
          clipBehavior: Clip.none,
          children: [
            if (animatedTrophyBackground != null)
              Positioned(
                  top: lottieTopSpacing,
                  left: lottieHorizontal,
                  right: lottieHorizontal,
                  // width: designSpec.lottieRegionSize,
                  // height: designSpec.lottieRegionSize,
                  child: LottieWidget(
                    uri: animatedTrophyBackground.url,
                    duration: animatedTrophyBackground.duration,
                    width: designSpec.lottieRegionSize,
                    height: designSpec.lottieRegionSize,
                    action: LottieAction.forward,
                  )),
            Positioned(
                top: lottieTopSpacing,
                left: lottieHorizontal,
                right: lottieHorizontal,
                child: LottieWidget(
                  uri: "assets/lottie/animated_trophy.json",
                  duration: const Duration(milliseconds: 485),
                  width: designSpec.lottieRegionSize,
                  height: designSpec.lottieRegionSize,
                  action: LottieAction.forward,
                  package: "daily_challenge",
                  imageProviderFactory: (image) {
                    Log.d("image ==> ${image.id}");
                    if (image.id == "trophy.png") {
                      final url = DailyChallengeManager.instance.getTrophyImage(
                          DateTimeUtils.generateYearMonthNum(yearMonth),
                          achieved: 0);
                      return () async {
                        return await _loadImage(AssetImage(url));
                      };
                    }
                  },
                )),
            Column(
              mainAxisSize: MainAxisSize.max,
              children: [
                SizedSpacer(height: titleTopSpacing),
                SizedBox(
                  height: designSpec.titleHeight,
                  child: AnimatedTransformBuilder.single(
                  duration: const Duration(milliseconds: 300),
                  delayed: const Duration(milliseconds: 150),
                  fromTranslation:
                      Offset(0.0, designSpec.measuredSize.height / 2),
                  toTranslation: Offset.zero,
                  child: ShaderMask(
                    shaderCallback: (rect) {
                      return const LinearGradient(
                              colors: [Color(0xFFFFEB96), Color(0xFFFAB10E)],
                              begin: Alignment.topCenter,
                              end: Alignment.bottomCenter)
                          .createShader(rect);
                    },
                    child: Text(
                      appStrings.congratulations,
                      style: TextStyle(
                          fontSize: designSpec.titleFontSize,
                          fontWeight: GuruTheme.fwExtraBold,
                          color: Colors.white,
                          shadows: [
                            Shadow(
                                color: Colors.black.withOpacity(0.5),
                                offset: const Offset(1, 1))
                          ]),
                    ),
                  ),
                )),
                SizedSpacer(height: titleBottomSpacing),
                SizedBox(
                  height: designSpec.summaryRegionHeight,
                  child: Padding(
                      padding: designSpec.summaryPadding,
                      child: AutoSizeText(
                          appStrings
                              .congratsSummary(MMMMyFormat.format(yearMonth)),
                          textAlign: TextAlign.center,
                          maxLines: 4,
                          style: TextStyle(
                              color: theme.summaryColor ?? Colors.white,
                              fontSize: designSpec.summaryFontSize,
                              height: 1.46))),
                ),
                SizedSpacer(height: summaryBottomSpacing),
                GuruButton(
                  size: Size(
                      screenWidth - (designSpec.buttonHorizontalSpacing * 2),
                      designSpec.buttonHeight),
                  sizeSpec: GuruButtonSizeSpec.s1,
                  style: theme.buttonStyle,
                  action: appStrings.collect,
                  onPressed: () {
                    DailyChallengeManager.instance.config.callbacks
                        ?.onCongratulationsPageCollect(yearMonth);
                    RouteCenter.instance.back();
                  },
                ),
                SizedSpacer(height: buttonBottomSpacing),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
