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/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/invoice/domain/blocs/invoices_list_bloc/invoice_bloc.dart';
import 'package:krow/features/invoice/domain/blocs/invoices_list_bloc/invoice_state.dart';
import 'package:krow/features/invoice/presentation/screens/invoices_list/invoice_list_item.dart';

import '../../../domain/blocs/invoices_list_bloc/invoice_event.dart';
import '../../../domain/invoice_entity.dart';

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

  @override
  State<InvoicesListMainScreen> createState() => _InvoicesListMainScreenState();
}

class _InvoicesListMainScreenState extends State<InvoicesListMainScreen> {
  final List<String> tabs = const [
    'All',
    'Open',
    'Disputed',
    'Resolved',
    'Paid',
    'Overdue',
    'Verified',
  ];

  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<InvoiceBloc>(context).add(
          LoadMoreInvoiceEvent(
              status: BlocProvider.of<InvoiceBloc>(context).state.tabIndex),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<InvoiceBloc, InvoicesState>(
      builder: (context, state) {
        List<InvoiceListEntity> items = state.tabs[state.tabIndex]!.items;

        return Scaffold(
          appBar: KwAppBar(
            titleText: 'Invoices',
            centerTitle: false,
          ),
          body: ScrollLayoutHelper(
            padding: const EdgeInsets.symmetric(vertical: 16),
            onRefresh: () async {
              BlocProvider.of<InvoiceBloc>(context)
                  .add(LoadTabInvoiceEvent(status: state.tabIndex));
            },
            controller: _scrollController,
            upperWidget: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                KwTabBar(
                    tabs: tabs,
                    onTap: (index) {
                      BlocProvider.of<InvoiceBloc>(context)
                          .add(InvoiceTabChangedEvent(tabIndex: index));
                    }),
                const Gap(16),
                if (state.tabs[state.tabIndex]!.inLoading &&
                    state.tabs[state.tabIndex]!.items.isEmpty)
                  ..._buildListLoading(),
                if (!state.tabs[state.tabIndex]!.inLoading && items.isEmpty)
                  ..._emptyListWidget(),
                RefreshIndicator(
                  onRefresh: () async {
                    BlocProvider.of<InvoiceBloc>(context)
                        .add(LoadTabInvoiceEvent(status: state.tabIndex));
                  },
                  child: ListView.builder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemCount: items.length,
                      itemBuilder: (context, index) {
                        return InvoiceListItemWidget(item: 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),
      const Text(
        'You currently have no Invoices',
        textAlign: TextAlign.center,
        style: AppTextStyles.headingH2,
      ),
    ];
  }
}
