import 'package:bart/bart.dart';
import 'package:flutter/material.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/bottom_menu/notification_bottom_item.dart';
import 'package:kasy_kit/core/navigation/kasy_navigation_config.dart';
import 'package:kasy_kit/core/navigation/kasy_route_transition.dart';
import 'package:kasy_kit/core/rating/widgets/rate_banner.dart';
import 'package:kasy_kit/core/theme/theme.dart';
import 'package:kasy_kit/features/home/design_system_page.dart';
import 'package:kasy_kit/features/home/home_components_page.dart';
import 'package:kasy_kit/features/home/home_components_preview_page.dart';
import 'package:kasy_kit/features/home/home_features_page.dart';
import 'package:kasy_kit/features/home/home_page.dart';
import 'package:kasy_kit/features/notifications/ui/notifications_page.dart';
import 'package:kasy_kit/features/settings/settings_page.dart';
import 'package:kasy_kit/i18n/translations.g.dart';

List<BartMenuRoute> subRoutes() {
  return [
    BartMenuRoute.bottomBar(
      label: t.navigation.home,
      icon: KasyIcons.home,
      path: 'home',
      pageBuilder: (_, _, settings) => const HomePage(),
      transitionDuration: bottomBarTransitionDuration,
      transitionsBuilder: bottomBarTransition,
    ),
    BartMenuRoute.bottomBar(
      label: t.navigation.wishlist,
      icon: KasyIcons.favorite,
      path: 'wishlist',
      pageBuilder: (_, _, settings) => const WishlistPage(),
      transitionDuration: bottomBarTransitionDuration,
      transitionsBuilder: bottomBarTransition,
    ),
    BartMenuRoute.bottomBarBuilder(
      label: t.navigation.notifications,
      builder: (_, isActive) => const BottomItemNotification(),
      path: 'notifications',
      pageBuilder: (_, _, settings) => NotificationsPage(),
      transitionDuration: bottomBarTransitionDuration,
      transitionsBuilder: bottomBarTransition,
    ),
    BartMenuRoute.bottomBar(
      label: t.navigation.settings,
      icon: KasyIcons.settings,
      path: 'settings',
      pageBuilder: (_, _, settings) => const SettingsPage(),
      transitionDuration: bottomBarTransitionDuration,
      transitionsBuilder: bottomBarTransition,
    ),
    BartMenuRoute.innerRoute(
      path: bartInnerPath('home', 'features'),
      showBottomBar: false,
      pageBuilder: (_, _, _) =>
          const _HomeInnerRoute(child: HomeFeaturesPage()),
      transitionDuration: bottomBarTransitionDuration,
      transitionsBuilder: bottomBarTransition,
    ),
    BartMenuRoute.innerRoute(
      path: bartInnerPath('home', 'components'),
      showBottomBar: false,
      pageBuilder: (_, _, _) =>
          const _HomeInnerRoute(child: HomeComponentsPage()),
      transitionDuration: bottomBarTransitionDuration,
      transitionsBuilder: bottomBarTransition,
    ),
    BartMenuRoute.innerRoute(
      path: bartInnerPath('home', 'design-system'),
      showBottomBar: false,
      pageBuilder: (_, _, _) =>
          const _HomeInnerRoute(child: DesignSystemPage()),
      transitionDuration: bottomBarTransitionDuration,
      transitionsBuilder: bottomBarTransition,
    ),
    BartMenuRoute.innerRoute(
      path: bartInnerPath('home', 'components-preview'),
      showBottomBar: false,
      pageBuilder: (_, _, settings) {
        final extra = settings?.arguments;
        if (extra is! HomeComponentPreviewRouteExtra) {
          return const PageFake();
        }
        return _HomeInnerRoute(
          child: HomeComponentsPreviewPage(
            title: extra.title,
            variants: extra.variants,
          ),
        );
      },
      transitionDuration: bottomBarTransitionDuration,
      transitionsBuilder: bottomBarTransition,
    ),
    BartMenuRoute.innerRoute(
      path: bartInnerPath('home', 'search'),
      showBottomBar: false,
      pageBuilder: (_, _, _) => const _HomeInnerRoute(child: PageFake()),
      transitionDuration: bottomBarTransitionDuration,
      transitionsBuilder: bottomBarTransition,
    ),
    BartMenuRoute.innerRoute(
      path: bartInnerPath('home', 'search/subscribe'),
      showBottomBar: false,
      pageBuilder: (_, _, _) => const _HomeInnerRoute(child: PageFake()),
      transitionDuration: bottomBarTransitionDuration,
      transitionsBuilder: bottomBarTransition,
    ),
  ];
}

class _HomeInnerRoute extends StatefulWidget {
  final Widget child;

  const _HomeInnerRoute({required this.child});

  @override
  State<_HomeInnerRoute> createState() => _HomeInnerRouteState();
}

class _HomeInnerRouteState extends State<_HomeInnerRoute> {
  ModalRoute<Object?>? _route;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final ModalRoute<Object?>? route = ModalRoute.of(context);
    if (_route != route) {
      _route?.animation?.removeStatusListener(_onRouteAnimStatus);
      _route = route;
      final Animation<double>? anim = route?.animation;
      if (anim != null && !anim.isCompleted) {
        anim.addStatusListener(_onRouteAnimStatus);
      }
    }
    kasyHideBottomBar(context);
  }

  void _onRouteAnimStatus(AnimationStatus status) {
    if (mounted && status == AnimationStatus.completed) {
      kasyHideBottomBar(context);
    }
  }

  @override
  void dispose() {
    _route?.animation?.removeStatusListener(_onRouteAnimStatus);
    super.dispose();
  }

  @override
  void reassemble() {
    super.reassemble();
    kasyHideBottomBar(context);
  }

  @override
  Widget build(BuildContext context) => widget.child;
}

/// Placeholder page for the wishlist tab.
/// Replace this with your own implementation.
class WishlistPage extends StatelessWidget {
  const WishlistPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: context.colors.background,
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          KasyAppBar(
          title: context.t.navigation.wishlist,
          style: KasyAppBarStyle.rootTab,
          ),
          Expanded(
            child: Padding(
              padding: EdgeInsets.fromLTRB(
                KasySpacing.pageHorizontalGutter,
                KasySpacing.belowChromeContentGap,
                KasySpacing.pageHorizontalGutter,
                MediaQuery.paddingOf(context).bottom +
                    KasySpacing.pageVerticalGutter,
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const RateBanner(forceInDebug: true),
                  Expanded(
                    child: Center(
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Container(
                            width: 80,
                            height: 80,
                            decoration: BoxDecoration(
                              color: context.colors.primary.withValues(
                                alpha: 0.12,
                              ),
                              shape: BoxShape.circle,
                            ),
                            child: Icon(
                              KasyIcons.favoriteOutline,
                              size: 40,
                              color: context.colors.primary,
                            ),
                          ),
                          const SizedBox(height: KasySpacing.md),
                          Text(
                            context.t.wishlist.empty_title,
                            style: context.textTheme.titleLarge?.copyWith(
                              color: context.colors.muted,
                            ),
                          ),
                          const SizedBox(height: KasySpacing.sm),
                          Text(
                            context.t.wishlist.empty_subtitle,
                            style: context.textTheme.bodyLarge?.copyWith(
                              color: context.colors.muted,
                            ),
                            textAlign: TextAlign.center,
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

/// This is a fake page to show how to use Bart
/// You can replace it with your own pages
class PageFake extends StatelessWidget {
  final Color? color;

  const PageFake({this.color, super.key});

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      // ignore: use_colored_box
      child: Container(
        color: color ?? context.colors.background,
        child: Column(
          children: [
            const RateBanner(forceInDebug: true),
            const SizedBox(height: 100),
            Opacity(opacity: 0.5, child: Text(context.t.bottom_router.fake_page_text)),
          ],
        ),
      ),
    );
  }
}

Widget bottomBarTransition(
  BuildContext context,
  Animation<double> animation,
  Animation<double> secondaryAnimation,
  Widget child,
) {
  return kasyBuildRouteTransition(
    context: context,
    animation: animation,
    secondaryAnimation: secondaryAnimation,
    child: child,
    kind: KasyNavigationConfig.bottomTab,
    fillColor: Colors.transparent,
  );
}

Duration get bottomBarTransitionDuration => KasyNavigationConfig.duration;
