import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:kasy_kit/components/components.dart';
import 'package:kasy_kit/core/data/api/analytics_api.dart';
import 'package:kasy_kit/core/rating/providers/rating_repository.dart';
import 'package:kasy_kit/core/states/user_state_notifier.dart';
import 'package:kasy_kit/core/theme/theme.dart';
import 'package:kasy_kit/core/widgets/responsive_layout.dart';
import 'package:kasy_kit/i18n/translations.g.dart';
import 'package:logger/logger.dart';

/// Shows the in-app review dialog. Prefer a stable [context] (not a sheet that
/// will be popped before the async work finishes).
Future<bool> showReviewDialog(
  BuildContext context,
  WidgetRef ref, {
  bool force = false,
}) async {
  if (!context.mounted) {
    return false;
  }

  final ratingRepository = ref.read(ratingRepositoryProvider);
  final analytics = ref.read(analyticsApiProvider);
  final userState = ref.read(userStateNotifierProvider);
  final rating = await ratingRepository.getReview(userState.user);

  final shouldAsk = rating.shouldAsk();
  Logger().d('should Ask for review: $shouldAsk');
  if (!shouldAsk && !force) {
    return false;
  }
  if (!context.mounted) {
    return false;
  }

  final bool? openFeedback = await showKasyDialog<bool>(
    context: context,
    barrierDismissible: false,
    builder: (dialogContext) {
      ratingRepository.delay();
      return Animate(
        effects: const [
          FadeEffect(
            delay: Duration(milliseconds: 100),
            duration: Duration(milliseconds: 300),
          ),
          MoveEffect(
            delay: Duration(milliseconds: 100),
            duration: Duration(milliseconds: 450),
            curve: Curves.easeOut,
            begin: Offset(0, 50),
            end: Offset.zero,
          ),
        ],
        child: DeviceSizeBuilder(
          builder: (device) {
            final maxWidth = switch (device) {
              DeviceType.medium =>
                MediaQuery.of(dialogContext).size.width - KasySpacing.xl,
              _ => 550.0,
            };
            final translations = Translations.of(dialogContext).review_popup;
            return KasyDialog(
              title: translations.title,
              titleCentered: true,
              showCloseButton: false,
              body: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Stack(
                    clipBehavior: Clip.none,
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(KasyRadius.md),
                        child: Image.asset(
                          'assets/images/review.png',
                          fit: BoxFit.fitWidth,
                          width: maxWidth,
                        ),
                      ),
                      Positioned(
                        top: KasySpacing.sm,
                        left: KasySpacing.sm,
                        child: CloseIcon(
                          onExit: () {
                            analytics.logEvent('rating_popup_close', {});
                            rating.delay().then((_) {
                              if (!dialogContext.mounted) return;
                              Navigator.of(dialogContext).pop();
                            });
                          },
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: KasySpacing.md),
                  Text(
                    translations.description,
                    textAlign: TextAlign.center,
                    style: Theme.of(dialogContext).textTheme.bodyMedium,
                  ),
                ],
              ),
              footer: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  KasyButton(
                    label: translations.rate_button,
                    expand: true,
                    onPressed: () {
                      analytics.logEvent('rating_popup_show', {});
                      ratingRepository.rate().then((_) => rating.review()).then(
                        (_) {
                          if (!dialogContext.mounted) return;
                          Navigator.of(dialogContext).pop();
                        },
                      );
                    },
                  ),
                  const SizedBox(height: KasySpacing.sm),
                  KasyButton(
                    label: translations.cancel_button,
                    variant: KasyButtonVariant.soft,
                    expand: true,
                    onPressed: () => Navigator.of(dialogContext).pop(true),
                  ),
                ],
              ),
            );
          },
        ),
      );
    },
  );

  if (openFeedback == true && context.mounted) {
    await context.push('/feedback');
  }
  return true;
}

class CloseIcon extends StatelessWidget {
  final VoidCallback onExit;

  const CloseIcon({super.key, required this.onExit});

  @override
  Widget build(BuildContext context) {
    return ClipOval(
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: () => onExit.call(),
          child: Ink(
            width: 32,
            height: 32,
            decoration: BoxDecoration(
              color: context.colors.background,
              shape: BoxShape.circle,
            ),
            child: Icon(
              KasyIcons.close,
              color: context.colors.onBackground,
              size: 21,
            ),
          ),
        ),
      ),
    );
  }
}
