import 'package:farm_tpf/data/repository/repository.dart';
import 'package:farm_tpf/presentation/custom_widgets/button/button_2_icon.dart';
import 'package:farm_tpf/presentation/custom_widgets/button/second_button.dart';
import 'package:farm_tpf/presentation/screens/codes/code_detail_page.dart';
import 'package:farm_tpf/presentation/screens/codes/create_stamp_page.dart';
import 'package:farm_tpf/presentation/screens/codes/models/stamp.dart';
import 'package:farm_tpf/presentation/screens/codes/widgets/item_code.dart';
import 'package:farm_tpf/themes/app_colors.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:get/get.dart';

import '../../../themes/styles_text.dart';
import '../../../utils/const_string.dart';
import '../../custom_widgets/bottom_loader.dart';
import '../../custom_widgets/loading_list_page.dart';
import '../plot/widget_search.dart';
import 'bloc/stamp_bloc.dart';

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

  @override
  State<CodePage> createState() => _CodePageState();
}

class _CodePageState extends State<CodePage> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  StampBloc bloc = StampBloc(Repository());
  final _scrollController = ScrollController();
  final _scrollThreshold = 250.0;

  @override
  void initState() {
    bloc.add(DataFetched());

    _scrollController.addListener(() {
      final maxScroll = _scrollController.position.maxScrollExtent;
      final currentScroll = _scrollController.position.pixels;
      if (maxScroll - currentScroll < _scrollThreshold) {
        bloc.add(DataFetched());
      }
    });
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      key: _scaffoldKey,
      body: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            SizedBox(
              height: 8,
            ),
            Container(
              padding: EdgeInsets.all(8),
              color: Colors.white,
              child: Text(
                'Danh sách tem',
                style: TextStyle(fontWeight: FontWeight.w500, fontSize: 22),
              ),
            ),
            WidgetSearch(),
            Row(
              children: [
                Button2Icon(
                  leftIcon: CupertinoIcons.arrow_up_arrow_down,
                  rightIcon: CupertinoIcons.chevron_down,
                  title: 'Sort',
                  onPressed: () {},
                ),
                Button2Icon(
                  leftIcon: CupertinoIcons.slider_horizontal_3,
                  title: 'Filter',
                  rightWidget: Container(
                    width: 16,
                    height: 16,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(12),
                      color: Colors.blue,
                    ),
                    child: Center(
                      child: Text(
                        '1',
                        style: StylesText.caption6.copyWith(color: Colors.white),
                      ),
                    ),
                  ),
                  onPressed: () {},
                ),
                const Spacer(),
                SecondButton(
                  onPressed: () {
                    Get.to(() => CreateStampPage())?.then((value) {
                      if (value != null) {
                        bloc.add(OnRefresh());
                      }
                    });
                  },
                  title: 'Tạo tem',
                  leftIcon: CupertinoIcons.add,
                  color: AppColors.primary1,
                  textColor: Colors.white,
                  borderColor: AppColors.primary1,
                ),
              ],
            ),
            Expanded(
              child: mainBody(),
            ),
          ],
        ),
      ),
    );
  }

  Widget mainBody() {
    return BlocBuilder<StampBloc, StampState>(
      bloc: bloc,
      builder: (context, state) {
        if (state is StampFailure) {
          return Center(child: Text(state.errorString));
        }
        if (state is StampSuccess) {
          if ((state.items ?? []).isEmpty) {
            return Center(child: Text(label_list_empty));
          }
          return RefreshIndicator(
              child: ListView.builder(
                physics: AlwaysScrollableScrollPhysics(),
                itemBuilder: (BuildContext context, int index) {
                  return index >= (state.items ?? []).length
                      ? BottomLoader()
                      : ItemCode(
                          item: state.items?[index],
                          onPressed: () {
                            Get.to(() => CodeDetailPage());
                          },
                        );
                },
                itemCount: (state.hasReachedMax ?? false) ? (state.items ?? []).length : (state.items ?? []).length + 1,
                controller: _scrollController,
              ),
              onRefresh: () async {
                bloc.add(OnRefresh());
              });
        }
        return Center(
          child: LoadingListPage(),
        );
      },
    );
  }
}
