import 'package:cargocalculaterapp/core/extension/build_context_extension.dart';
import 'package:cargocalculaterapp/core/local_source/local_source.dart';
import 'package:cargocalculaterapp/core/utils/app_utils.dart';
import 'package:cargocalculaterapp/core/widgets/loading/custom_loading.dart';
import 'package:cargocalculaterapp/features/home/presentation/pages/widgets/banners_widget.dart';
import 'package:cargocalculaterapp/features/home/presentation/pages/widgets/empty_order_widget.dart';
import 'package:cargocalculaterapp/features/home/presentation/pages/widgets/order_list_shimmer.dart';
import 'package:cargocalculaterapp/features/home/presentation/pages/widgets/orders_list_widget.dart';
import 'package:cargocalculaterapp/features/home/presentation/pages/widgets/status_list_widget.dart';
import 'package:cargocalculaterapp/generated/l10n.dart';
import 'package:cargocalculaterapp/router/name_routes.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import '../../../../injector_container.dart';
import '../bloc/home_bloc.dart';
import '../mixin/home_mixin.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

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

class _HomePageState extends State<HomePage> with HomeMixin {
  @override
  void initState() {
    context.read<HomeBloc>().add(const GetAllOrdersListEvent());
    context.read<HomeBloc>().add(const GetBannersEvent());
    initControllers();
    _scrollListener();
    super.initState();
  }

  void _scrollListener() {
    scrollController.addListener(() {
      final state = context.read<HomeBloc>().state;
      if (scrollController.position.pixels >=
              scrollController.position.maxScrollExtent - 200 &&
          !state.paginationLoading &&
          state.page <= (state.pageCount ?? 1)) {
        context.read<HomeBloc>().add(const PaginationEvent());
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<HomeBloc, HomeState>(
      builder: (context, state) {
        return Scaffold(
          backgroundColor: context.color.grayBackground,
          appBar: AppBar(
            title: Row(
              children: [
                GestureDetector(
                  onTap: () {
                    Clipboard.setData(
                      ClipboardData(text: sl<LocalSource>().getUCode()),
                    );
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        content: Text(AppLocalization.current.text_copied),
                      ),
                    );
                  },
                  child: Text(
                    sl<LocalSource>().getUCode(),
                    style: context.text.secondaryText14,
                  ),
                ),
                const Spacer(),
                Text(AppLocalization.current.orders),
                const Spacer(),
              ],
            ),
            automaticallyImplyLeading: false,
            actions: [
              IconButton(
                onPressed: () {
                  Navigator.pushNamed(context, Routes.notification);
                },
                icon: SvgPicture.asset(
                  "assets/svg/ic_notification.svg",
                  colorFilter: ColorFilter.mode(
                    context.color.textColor,
                    BlendMode.srcIn,
                  ),
                ),
              ),
              AppUtils.kBoxWith12,
            ],
          ),
          body: CustomScrollView(
            controller: scrollController,
            physics: const BouncingScrollPhysics(
              parent: AlwaysScrollableScrollPhysics(),
            ),
            slivers: [
              StatusListWidget(selectedStatus: state.selectedStatus),
              CupertinoSliverRefreshControl(
                onRefresh: () async {
                  context.read<HomeBloc>().add(const RefreshEvent());
                  await Future<void>.delayed(
                    const Duration(milliseconds: 1500),
                  );
                },
              ),
              if (state.banners?.isNotEmpty ?? false)
                BannersWidget(banners: state.banners),
              state.isLoading
                  ? const OrderListShimmer()
                  : (state.ordersList?.data?.length ?? 0) > 0
                  ? OrdersListWidget(data: state.ordersList?.data)
                  : const EmptyOrderWidget(),
              if (state.paginationLoading)
                const SliverPadding(
                  padding: AppUtils.kPaddingAll24,
                  sliver: SliverToBoxAdapter(
                    child: Center(child: CustomLoadingWidget()),
                  ),
                ),
            ],
          ),
        );
      },
    );
  }

  @override
  void dispose() {
    disposeControllers();
    scrollController.removeListener(_scrollListener);
    super.dispose();
  }
}
