import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:kasy_kit/components/kasy_app_bar.dart';
import 'package:kasy_kit/core/bottom_menu/bart_inner_paths.dart';
import 'package:kasy_kit/core/bottom_menu/kasy_bart_navigation.dart';
import 'package:kasy_kit/core/haptics/kasy_haptics.dart';
import 'package:kasy_kit/core/states/components/maybe_ask_rating.dart';
import 'package:kasy_kit/core/states/components/maybe_show_update_bottom_sheet.dart';
import 'package:kasy_kit/core/states/components/maybeshow_component.dart';
import 'package:kasy_kit/core/theme/theme.dart';
import 'package:kasy_kit/features/home/home_components_page.dart';
import 'package:kasy_kit/features/home/home_features_page.dart';
import 'package:kasy_kit/features/notifications/shared/att_permission.dart';
import 'package:kasy_kit/features/subscription/shared/maybeshow_premium.dart';
import 'package:kasy_kit/i18n/translations.g.dart';

/// Home hub with dashboard cards; features live under [HomeFeaturesPage].
class HomePage extends ConsumerWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final bool isDark = Theme.of(context).brightness == Brightness.dark;
    return ConditionalWidgetsEvents(
      eventWidgets: [
        MaybeAskForReview(),
        MaybeAskForRating(),
        MaybeShowPremiumPage(),
        MaybeShowUpdateBottomSheet(),
        MaybeShowAttPermission(),
      ],
      child: ColoredBox(
        color: context.colors.background,
        child: Stack(
          children: [
            CustomScrollView(
              slivers: [
                SliverToBoxAdapter(
                  child: SizedBox(height: kasyAppBarBodyTopOverlap(context)),
                ),
                SliverPadding(
                  padding: EdgeInsets.only(
                    left: KasySpacing.pageHorizontalGutter,
                    right: KasySpacing.pageHorizontalGutter,
                    top: KasySpacing.belowChromeContentGap,
                    bottom: MediaQuery.paddingOf(context).bottom,
                  ),
                  sliver: SliverList(
                    delegate: SliverChildListDelegate([
                      LayoutBuilder(
                        builder: (context, constraints) {
                          final isWide = constraints.maxWidth > 600;
                          final featuresCard = _DashboardGradientCard(
                            countLabel: t.home.dashboard.count_total(
                              count: homeFeaturesEntryCount(),
                            ),
                            countBadgeTextColor: const Color(0xFF4A3D6B),
                            title: t.home.dashboard.features_title,
                            subtitle: t.home.dashboard.features_subtitle,
                            gradient: _featuresGradient(context, isDark),
                            onOpen: () {
                              KasyHaptics.medium(context);
                              Navigator.of(context)
                                  .pushNamed(bartInnerPath('home', 'features'))
                                  .then((_) {
                                if (context.mounted) {
                                  kasyShowBottomBar(context);
                                }
                              });
                            },
                          );
                          final componentsCard = _DashboardGradientCard(
                            countLabel: t.home.dashboard.count_total(
                              count: HomeComponentsPage.sectionCount,
                            ),
                            countBadgeTextColor: const Color(0xFF2D3A4D),
                            title: t.home.dashboard.components_title,
                            subtitle: t.home.dashboard.components_subtitle,
                            gradient: _componentsGradient(context, isDark),
                            onOpen: () {
                              KasyHaptics.medium(context);
                              Navigator.of(context)
                                  .pushNamed(
                                    bartInnerPath('home', 'components'),
                                  )
                                  .then((_) {
                                if (context.mounted) {
                                  kasyShowBottomBar(context);
                                }
                              });
                            },
                          );
                          if (isWide) {
                            return Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Expanded(child: featuresCard),
                                const SizedBox(width: KasySpacing.md),
                                Expanded(child: componentsCard),
                              ],
                            );
                          }
                          return Column(
                            children: [
                              featuresCard,
                              const SizedBox(height: KasySpacing.md),
                              componentsCard,
                            ],
                          );
                        },
                      ),
                      const SizedBox(height: KasySpacing.xl),
                    ]),
                  ),
                ),
              ],
            ),
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              child: KasyAppBar(
                title: t.home.dashboard.brand,
                style: KasyAppBarStyle.rootTab,
                onThemeToggle: () {
                  KasyHaptics.light(context);
                  ThemeProvider.of(context).toggle();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// Soft product-style gradients (calm blues / lilac); same geometry, distinct hue.
  static LinearGradient _componentsGradient(
    BuildContext context,
    bool isDark,
  ) {
    if (isDark) {
      return LinearGradient(
        begin: Alignment.topLeft,
        end: Alignment.bottomRight,
        colors: [
          context.colors.primary.withValues(alpha: 0.32),
          const Color(0xFF2D3A4D).withValues(alpha: 0.92),
          const Color(0xFF353D52).withValues(alpha: 0.88),
        ],
      );
    }
    return const LinearGradient(
      begin: Alignment.topLeft,
      end: Alignment.bottomRight,
      colors: [
        Color(0xFFDCE6FF),
        Color(0xFFF0F6FF),
        Color(0xFFE2E8F6),
      ],
    );
  }

  static LinearGradient _featuresGradient(BuildContext context, bool isDark) {
    if (isDark) {
      return LinearGradient(
        begin: Alignment.topLeft,
        end: Alignment.bottomRight,
        colors: [
          const Color(0xFF4A3D6B).withValues(alpha: 0.94),
          const Color(0xFF4F3D58).withValues(alpha: 0.9),
          context.colors.primary.withValues(alpha: 0.22),
        ],
      );
    }
    return const LinearGradient(
      begin: Alignment.topLeft,
      end: Alignment.bottomRight,
      colors: [
        Color(0xFFE2D8FC),
        Color(0xFFF5ECFA),
        Color(0xFFDCE8FF),
      ],
    );
  }
}

class _DashboardGradientCard extends StatelessWidget {
  final String countLabel;
  final Color countBadgeTextColor;
  final String title;
  final String subtitle;
  final LinearGradient gradient;
  final VoidCallback onOpen;

  const _DashboardGradientCard({
    required this.countLabel,
    required this.countBadgeTextColor,
    required this.title,
    required this.subtitle,
    required this.gradient,
    required this.onOpen,
  });

  @override
  Widget build(BuildContext context) {
    final bool isDark = Theme.of(context).brightness == Brightness.dark;
    final Color titleColor =
        isDark ? Colors.white : const Color(0xFF1A1D26);
    final Color subtitleColor = titleColor.withValues(alpha: 0.62);
    final Color arrowCircleColor = isDark
        ? Colors.black.withValues(alpha: 0.38)
        : Colors.white.withValues(alpha: 0.82);
    final Color arrowIconColor =
        isDark ? Colors.white : const Color(0xFF1A1D26);
    final Color countBadgeFill = isDark
        ? Colors.white.withValues(alpha: 0.14)
        : Colors.white.withValues(alpha: 0.38);
    final Color countBadgeBorder = isDark
        ? Colors.white.withValues(alpha: 0.24)
        : Colors.black.withValues(alpha: 0.06);
    final Color countBadgeLabelColor =
        isDark ? Colors.white.withValues(alpha: 0.94) : countBadgeTextColor;
    final Color cardOutlineColor = context.colors.outline.withValues(
      alpha: isDark ? 0.34 : 0.30,
    );
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onOpen,
        borderRadius: BorderRadius.circular(28),
        child: Ink(
          height: 156,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(28),
            gradient: gradient,
            border: Border.all(color: cardOutlineColor),
          ),
          child: Padding(
            padding: const EdgeInsets.all(KasySpacing.md + 2),
            child: Stack(
              children: [
                Positioned(
                  left: 0,
                  top: 0,
                  child: DecoratedBox(
                    decoration: BoxDecoration(
                      color: countBadgeFill,
                      borderRadius: BorderRadius.circular(
                        KasyRadius.full,
                      ),
                      border: Border.all(color: countBadgeBorder),
                    ),
                    child: Padding(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 12,
                        vertical: 6,
                      ),
                      child: Text(
                        countLabel,
                        style: context.textTheme.labelMedium?.copyWith(
                          color: countBadgeLabelColor,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                ),
                Positioned(
                  left: 0,
                  right: 56,
                  bottom: 0,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        title,
                        style: context.textTheme.headlineSmall?.copyWith(
                          fontWeight: FontWeight.w800,
                          color: titleColor,
                          letterSpacing: -0.3,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        subtitle,
                        style: context.textTheme.bodyMedium?.copyWith(
                          color: subtitleColor,
                          fontWeight: FontWeight.w400,
                        ),
                      ),
                    ],
                  ),
                ),
                Positioned(
                  right: 0,
                  bottom: 0,
                  child: Material(
                    color: arrowCircleColor,
                    shape: const CircleBorder(),
                    child: InkWell(
                      customBorder: const CircleBorder(),
                      onTap: onOpen,
                      child: Padding(
                        padding: const EdgeInsets.all(12),
                        child: Icon(
                          KasyIcons.northEast,
                          size: 20,
                          color: arrowIconColor,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
