import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:line_icons/line_icons.dart';

import '../../../application/analytic/exclusive_summary_loader/exclusive_summary_loader_bloc.dart';
import '../../../application/home/home_bloc.dart';
import '../../../application/outlet/outlet_list_loader/outlet_list_loader_bloc.dart';
import '../../../application/outlet/selected_outlet/selected_outlet_bloc.dart';
import '../../../common/constant/app_constant.dart';
import '../../../common/theme/theme.dart';
import '../../../injection.dart';
import '../../components/button/button.dart';
import '../../components/spacer/spacer.dart';
import 'widgets/feature.dart';
import 'widgets/header.dart';
import 'widgets/home_top_products.dart';
import 'widgets/home_warnings.dart';
import 'widgets/profit_sharing_banner.dart';
import 'widgets/stats.dart';

@RoutePage()
class HomePage extends StatefulWidget implements AutoRouteWrapper {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();

  @override
  Widget wrappedRoute(BuildContext context) => MultiBlocProvider(
    providers: [
      BlocProvider(
        create: (context) =>
            getIt<HomeBloc>()..add(HomeEvent.fetchedDashboard()),
      ),
      BlocProvider(
        create: (context) =>
            getIt<OutletListLoaderBloc>()
              ..add(const OutletListLoaderEvent.fetched()),
      ),
      BlocProvider(
        create: (context) =>
            getIt<SelectedOutletBloc>()
              ..add(const SelectedOutletEvent.loaded()),
      ),
      BlocProvider(create: (context) => getIt<ExclusiveSummaryLoaderBloc>()),
    ],
    child: this,
  );
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  late AnimationController _headerAnimationController;
  late AnimationController _contentAnimationController;

  @override
  void initState() {
    super.initState();

    _headerAnimationController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );

    _contentAnimationController = AnimationController(
      duration: const Duration(milliseconds: 1200),
      vsync: this,
    );

    _startAnimations();
  }

  void _startAnimations() {
    _headerAnimationController.forward();
    Future.delayed(const Duration(milliseconds: 200), () {
      _contentAnimationController.forward();
    });
  }

  @override
  void dispose() {
    _headerAnimationController.dispose();
    _contentAnimationController.dispose();
    super.dispose();
  }

  void _refetchDashboard(BuildContext context) {
    context.read<HomeBloc>().add(HomeEvent.fetchedDashboard());
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<SelectedOutletBloc, SelectedOutletState>(
      listenWhen: (previous, current) =>
          previous.selectedOutletId != current.selectedOutletId,
      listener: (context, state) => _refetchDashboard(context),
      child: Scaffold(
        backgroundColor: AppColor.background,
        body: RefreshIndicator(
          backgroundColor: AppColor.white,
          color: AppColor.primary,
          onRefresh: () {
            _refetchDashboard(context);
            return Future.value();
          },
          child: BlocBuilder<HomeBloc, HomeState>(
            builder: (context, state) {
              return CustomScrollView(
                physics: const BouncingScrollPhysics(
                  parent: ClampingScrollPhysics(),
                ),
                slivers: [
                  // SliverAppBar with HomeHeader as background
                  SliverAppBar(
                    expandedHeight: 440, // Adjusted for new header with slider
                    floating: false,
                    pinned: true,
                    snap: false,
                    elevation: 0,
                    scrolledUnderElevation: 8,
                    backgroundColor: AppColor.primary,
                    surfaceTintColor: Colors.transparent,
                    flexibleSpace: LayoutBuilder(
                      builder: (BuildContext context, BoxConstraints constraints) {
                        // Calculate collapse progress (0.0 = expanded, 1.0 = collapsed)
                        final double expandedHeight = 200;
                        final double collapsedHeight =
                            kToolbarHeight + MediaQuery.of(context).padding.top;
                        final double currentHeight = constraints.maxHeight;

                        double collapseProgress =
                            1.0 -
                            ((currentHeight - collapsedHeight) /
                                (expandedHeight - collapsedHeight));
                        collapseProgress = collapseProgress.clamp(0.0, 1.0);

                        return FlexibleSpaceBar(
                          title: Opacity(
                            opacity:
                                collapseProgress, // Title muncul saat collapse
                            child: Row(
                              children: [
                                Expanded(
                                  child: Text(
                                    AppConstant.appName,
                                    style: AppStyle.xl.copyWith(
                                      fontWeight: FontWeight.w700,
                                      fontSize: 18,
                                      letterSpacing: -0.5,
                                      color: AppColor.white,
                                    ),
                                  ),
                                ),
                                ActionIconButton(
                                  onTap: () {},
                                  icon: LineIcons.bell,
                                ),
                              ],
                            ),
                          ),
                          titlePadding: const EdgeInsets.only(
                            left: 20,
                            right: 12,
                            bottom: 16,
                          ),
                          background: AnimatedBuilder(
                            animation: _headerAnimationController,
                            builder: (context, child) {
                              return Transform.translate(
                                offset: Offset(
                                  0,
                                  50 * (1 - _headerAnimationController.value),
                                ),
                                child: Opacity(
                                  opacity: _headerAnimationController.value,
                                  child: HomeHeader(
                                    totalRevenue:
                                        state.dashboard.overview.totalSales,
                                  ),
                                ),
                              );
                            },
                          ),
                        );
                      },
                    ),
                  ),

                  // Main Content
                  SliverToBoxAdapter(
                    child: AnimatedBuilder(
                      animation: _contentAnimationController,
                      builder: (context, child) {
                        return Transform.translate(
                          offset: Offset(
                            0,
                            30 * (1 - _contentAnimationController.value),
                          ),
                          child: Opacity(
                            opacity: _contentAnimationController.value,
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                HomeFeature(),
                                HomeProfitSharingBanner(),
                                HomeWarnings(),
                                HomeStats(overview: state.dashboard.overview),
                                HomeTopProducts(
                                  products: state.dashboard.topProducts,
                                ),
                                const SpaceHeight(40),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                ],
              );
            },
          ),
        ),
      ), // Scaffold
    ); // BlocListener
  }
}
