import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:gap/gap.dart';
import 'package:krow/core/entity/event_entity.dart';
import 'package:krow/core/presentation/gen/assets.gen.dart';
import 'package:krow/core/presentation/styles/kw_text_styles.dart';
import 'package:krow/core/presentation/styles/theme.dart';
import 'package:krow/core/presentation/widgets/scroll_layout_helper.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_app_bar.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_option_selector.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_tabs.dart';
import 'package:krow/features/events/domain/blocs/events_list_bloc/events_bloc.dart';
import 'package:krow/features/events/domain/blocs/events_list_bloc/events_event.dart';
import 'package:krow/features/events/domain/blocs/events_list_bloc/events_state.dart';
import 'package:krow/features/events/presentation/lists/event_list_item_widget.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';

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

  @override
  State<EventsListMainScreen> createState() => _EventsListMainScreenState();

  @override
  Widget wrappedRoute(BuildContext context) {
    return BlocProvider<EventsBloc>(
      create: (context) => EventsBloc()..add(const EventsInitialEvent()),
      child: this,
    );
  }
}

class _EventsListMainScreenState extends State<EventsListMainScreen> {
  final tabs = <String, List<String>>{
    'Upcoming': ['Pending', 'Assigned', 'Confirmed'],
    'Active': ['Ongoing', 'Finished'],
    'Past': ['Completed', 'Closed', 'Canceled'],
    'Drafts': [],
  };

  late ScrollController _scrollController;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _scrollController.removeListener(_onScroll);
    _scrollController.dispose();
    super.dispose();
  }

  void _onScroll() {
    if (_scrollController.position.atEdge) {
      if (_scrollController.position.pixels != 0) {
        BlocProvider.of<EventsBloc>(context).add(
          LoadMoreEventEvent(
              tabIndex: BlocProvider.of<EventsBloc>(context).state.tabIndex,
              subTabIndex:
                  BlocProvider.of<EventsBloc>(context).state.subTabIndex),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<EventsBloc, EventsState>(
      listenWhen: (previous, current) =>
          previous.errorMessage != current.errorMessage,
      listener: (context, state) {
        if (state.errorMessage != null) {
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(
            content: Text(state.errorMessage!),
          ));
        }
      },
      builder: (context, state) {
        var tabState = state.tabs[state.tabIndex]![state.subTabIndex]!;
        List<EventEntity> items = tabState.items;

        return Scaffold(
          appBar: KwAppBar(
            titleText: 'Events',
            centerTitle: false,
          ),
          body: ModalProgressHUD(
            inAsyncCall: tabState.inLoading && tabState.items.isNotEmpty,
            child: ScrollLayoutHelper(
              padding: const EdgeInsets.symmetric(vertical: 16),
              onRefresh: () async {
                BlocProvider.of<EventsBloc>(context).add(LoadTabEventEvent(
                    tabIndex: state.tabIndex, subTabIndex: state.subTabIndex));
              },
              controller: _scrollController,
              upperWidget: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  KwTabBar(
                      tabs: tabs.keys.toList(),
                      flexes: const [7, 5, 5, 5],
                      onTap: (index) {
                        BlocProvider.of<EventsBloc>(context)
                            .add(EventsTabChangedEvent(tabIndex: index));
                      }),
                  const Gap(24),
                  _buildSubTab(state, context),
                  if (tabState.inLoading && tabState.items.isEmpty)
                    ..._buildListLoading(),
                  if (!tabState.inLoading && items.isEmpty)
                    ..._emptyListWidget(),
                  RefreshIndicator(
                    onRefresh: () async {
                      BlocProvider.of<EventsBloc>(context).add(
                          LoadTabEventEvent(
                              tabIndex: state.tabIndex,
                              subTabIndex: state.subTabIndex));
                    },
                    child: ListView.builder(
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        itemCount: items.length,
                        itemBuilder: (context, index) {
                          return EventListItemWidget(
                            item: items[index],
                          );
                        }),
                  ),
                ],
              ),
              lowerWidget: const SizedBox.shrink(),
            ),
          ),
        );
      },
    );
  }

  Widget _buildSubTab(EventsState state, BuildContext context) {
    if (state.tabs[state.tabIndex]!.length > 1) {
      return Stack(
        children: [
          Positioned(
              left: 16,
              right: 16,
              bottom: 25.5,
              child: Container(
                height: 1,
                color: AppColors.blackGray,
              )),
          Padding(
            padding: const EdgeInsets.only(bottom: 24, left: 16, right: 16),
            child: KwOptionSelector(
                selectedIndex: state.subTabIndex,
                onChanged: (index) {
                  BlocProvider.of<EventsBloc>(context)
                      .add(EventsSubTabChangedEvent(subTabIndex: index));
                },
                height: 26,
                selectorHeight: 4,
                textStyle: AppTextStyles.bodyMediumReg
                    .copyWith(color: AppColors.blackGray),
                selectedTextStyle: AppTextStyles.bodyMediumMed,
                itemAlign: Alignment.topCenter,
                items: tabs[tabs.keys.toList()[state.tabIndex]]!),
          ),
        ],
      );
    } else {
      return const SizedBox.shrink();
    }
  }

  List<Widget> _buildListLoading() {
    return [
      const Gap(116),
      const Center(child: CircularProgressIndicator()),
    ];
  }

  List<Widget> _emptyListWidget() {
    return [
      const Gap(100),
      Container(
        height: 64,
        width: 64,
        decoration: BoxDecoration(
          color: AppColors.grayWhite,
          borderRadius: BorderRadius.circular(32),
        ),
        child: Center(child: Assets.images.icons.xCircle.svg()),
      ),
      const Gap(24),
      const Text(
        'You currently have no event',
        textAlign: TextAlign.center,
        style: AppTextStyles.headingH2,
      ),
    ];
  }
}
