import 'package:auto_route/auto_route.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:gap/gap.dart';
import 'package:krow/core/application/routing/routes.gr.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_tabs.dart';
import 'package:krow/features/shifts/domain/blocs/shifts_list_bloc/shifts_bloc.dart';
import 'package:krow/features/shifts/domain/blocs/shifts_list_bloc/shifts_event.dart';
import 'package:krow/features/shifts/domain/blocs/shifts_list_bloc/shifts_state.dart';
import 'package:krow/features/shifts/domain/services/shift_completer_service.dart';
import 'package:krow/features/shifts/domain/shift_entity.dart';
import 'package:krow/features/shifts/presentation/widgets/shift_item_widget.dart';

@RoutePage()
class ShiftsListMainScreen extends StatefulWidget {
  const ShiftsListMainScreen({super.key});

  @override
  State<ShiftsListMainScreen> createState() => _ShiftsListMainScreenState();
}

class _ShiftsListMainScreenState extends State<ShiftsListMainScreen> {
  late AppLifecycleListener _appLifecycleListener;
  var dialogOpened = false;
  final List<String> tabs =  [
    'assigned',
    'confirmed',
    'active',
    'completed',
    'canceled'
  ];

  late ScrollController _scrollController;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      BlocProvider.of<ShiftsBloc>(context).add(
        LoadTabShiftEvent(
            status: BlocProvider.of<ShiftsBloc>(context).state.tabIndex),
      );
      BlocProvider.of<ShiftsBloc>(context).add(
        const ReloadMissingBreakShift(),
      );
    });
  }

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

    _appLifecycleListener = AppLifecycleListener(onStateChange: (state) {
      if (state == AppLifecycleState.resumed) {
        BlocProvider.of<ShiftsBloc>(context).add(
          const ReloadMissingBreakShift(),
        );
      }
    });
    _scrollController = ScrollController();
    _scrollController.addListener(_onScroll);
  }

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

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

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<ShiftsBloc, ShiftsState>(
      listenWhen: (oldState, state) {
        return state.missedShifts.isNotEmpty &&
            (oldState.missedShifts.isEmpty ||
                oldState.missedShifts.first.id != state.missedShifts.first.id);
      },
      listener: (context, state) async {
        if (state.missedShifts.isNotEmpty) {
          if(dialogOpened) return;
          dialogOpened = true;
          await ShiftCompleterService().startCompleteProcess(
            context,
            canSkip: false,
            state.missedShifts.first,
            onComplete: () {},
          );
          dialogOpened = false;

          BlocProvider.of<ShiftsBloc>(context).add(
            const ReloadMissingBreakShift(),
          );
        }
      },
      builder: (context, state) {
        List<ShiftEntity> items = state.tabs[state.tabIndex]!.items;
        return Scaffold(
          appBar: KwAppBar(
            titleText: 'your_shifts'.tr(),
            showNotification: true,
            centerTitle: false,
          ),
          body: ScrollLayoutHelper(
            padding: const EdgeInsets.symmetric(vertical: 16),
            onRefresh: () async {
              BlocProvider.of<ShiftsBloc>(context)
                  .add(const ReloadMissingBreakShift());
              BlocProvider.of<ShiftsBloc>(context)
                  .add(LoadTabShiftEvent(status: state.tabIndex));
            },
            controller: _scrollController,
            upperWidget: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                KwTabBar(
                    key: const Key('shifts_tab_bar'),
                    tabs: tabs.map((e) => e.tr()).toList(),
                    onTap: (index) {
                      BlocProvider.of<ShiftsBloc>(context)
                          .add(ShiftsTabChangedEvent(tabIndex: index));
                    }),
                const Gap(16),
                if (state.tabs[state.tabIndex]!.isLoading &&
                    state.tabs[state.tabIndex]!.items.isEmpty)
                  ..._buildListLoading(),
                if (!state.tabs[state.tabIndex]!.isLoading && items.isEmpty)
                  ..._emptyListWidget(),
                RefreshIndicator(
                  onRefresh: () async {
                    BlocProvider.of<ShiftsBloc>(context)
                        .add(LoadTabShiftEvent(status: state.tabIndex));
                  },
                  child: ListView.builder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemCount: items.length,
                      itemBuilder: (context, index) {
                        return ShiftItemWidget(
                          items[index],
                          bottomPadding: 12,
                          onPressed: () {
                            context.pushRoute(
                              ShiftDetailsRoute(shift: items[index]),
                            );
                          },
                        );
                      }),
                ),
              ],
            ),
            lowerWidget: 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),
       Text(
        'you_currently_have_no_shifts'.tr(),
        textAlign: TextAlign.center,
        style: AppTextStyles.headingH2,
      ),
    ];
  }
}
