import 'package:farm_tpf/data/repository/repository.dart';
import 'package:farm_tpf/models/index.dart';
import 'package:farm_tpf/presentation/custom_widgets/bottom_loader.dart';
import 'package:farm_tpf/presentation/custom_widgets/loading_list_page.dart';
import 'package:farm_tpf/presentation/screens/plot/widget_search.dart';
import 'package:farm_tpf/presentation/screens/plot_detail/sc_plot_detail.dart';
import 'package:farm_tpf/utils/const_assets.dart';
import 'package:farm_tpf/utils/const_color.dart';
import 'package:farm_tpf/utils/pref.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:farm_tpf/utils/const_string.dart';
import 'package:farm_tpf/utils/formatter.dart';
import 'package:get/get.dart';

import 'bloc/plot_bloc.dart';

class PlotListScreen extends StatefulWidget {
  @override
  _PlotListScreenState createState() => _PlotListScreenState();
}

class _PlotListScreenState extends State<PlotListScreen> {
  var pref = LocalPref();
  var token;
  var client;
  String pushkey = "";
  String currentFullName = "";

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

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => PlotBloc(repository: Repository())..add(DataFetched()),
      child: HoldInfinityWidget(),
    );
  }
}

class HoldInfinityWidget extends StatelessWidget {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(backgroundColor: Colors.white, key: _scaffoldKey, body: SafeArea(child: InfinityView()));
  }
}

class InfinityView extends StatefulWidget {
  @override
  _InfinityViewState createState() => _InfinityViewState();
}

class _InfinityViewState extends State<InfinityView> {
  final _scrollController = ScrollController();
  final _scrollThreshold = 250.0;
  late PlotBloc _plotBloc;

  @override
  void initState() {
    _scrollController.addListener(() {
      final maxScroll = _scrollController.position.maxScrollExtent;
      final currentScroll = _scrollController.position.pixels;
      if (maxScroll - currentScroll < _scrollThreshold) {
        _plotBloc.add(DataFetched());
      }
    });
    _plotBloc = BlocProvider.of<PlotBloc>(context);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        const SizedBox(
          height: 8,
        ),
        Container(
            padding: const EdgeInsets.all(8),
            color: Colors.white,
            child: const Text(
              'Danh sách lô trồng',
              style: TextStyle(fontWeight: FontWeight.w500, fontSize: 22),
            )),
        WidgetSearch(),
        Expanded(child: BlocBuilder<PlotBloc, PlotState>(
          builder: (context, state) {
            if (state is PlotFailure) {
              return Center(child: Text(state.errorString));
            }
            if (state is PlotSuccess) {
              if (state.items.isEmpty) {
                return const Center(child: Text(label_list_empty));
              }
              return RefreshIndicator(
                  child: ListView.builder(
                    physics: const AlwaysScrollableScrollPhysics(),
                    itemBuilder: (BuildContext context, int index) {
                      return index >= state.items.length ? BottomLoader() : ItemInfinityWidget(item: state.items[index]);
                    },
                    itemCount: state.hasReachedMax ? state.items.length : state.items.length + 1,
                    controller: _scrollController,
                  ),
                  onRefresh: () async {
                    _plotBloc.add(OnRefresh());
                  });
            }
            return Center(
              child: LoadingListPage(),
            );
          },
        ))
      ],
    );
  }

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

class ItemInfinityWidget extends StatelessWidget {
  final Crop item;

  const ItemInfinityWidget({Key? key, required this.item}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var backgroundColor;
    var textColor;
    switch (item.status) {
      case "STATUS_ARE_ACTIVE":
        backgroundColor = Colors.white;
        textColor = AppColors.DEFAULT;
        break;
      case "STATUS_FINISHED":
        backgroundColor = AppColors.DEFAULT;
        textColor = Colors.white;
        break;
      default:
        backgroundColor = Colors.white;
        textColor = Colors.black;
    }

    return InkWell(
        child: Container(
          margin: const EdgeInsets.all(8),
          decoration: BoxDecoration(
              color: backgroundColor,
              border: Border.all(color: Colors.grey, width: 0.35),
              borderRadius: BorderRadius.circular(8),
              boxShadow: [BoxShadow(color: Colors.grey, blurRadius: 3, offset: const Offset(0, 3))]),
          padding: const EdgeInsets.all(8),
          child: Row(
            children: [
              Container(
                child: Stack(
                  children: [
                    Image.asset(
                      AppAssets.tempImage,
                      width: 65,
                      height: 65,
                    ),
                    Positioned(
                      child: Container(
                        color: Colors.grey.withOpacity(0.5),
                        width: 65,
                        height: 20,
                        child: Text(item.areaM2?.formatNumtoStringDecimal().toString() ?? '' + " m\u00B2",
                            textAlign: TextAlign.center, style: const TextStyle(color: Colors.white)),
                      ),
                      bottom: 0,
                    )
                  ],
                ),
              ),
              const SizedBox(
                width: 12,
              ),
              Expanded(
                child: Container(
                  height: 75,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text("${item.code ?? ''} - ${item.suppliesName ?? ''}", style: TextStyle(color: textColor, fontWeight: FontWeight.bold)),
                      const Expanded(
                        child: SizedBox(),
                      ),
                      Row(
                        children: [
                          Icon(
                            Icons.access_time,
                            size: 16,
                            color: textColor,
                          ),
                          const SizedBox(
                            width: 4,
                          ),
                          Expanded(
                            child: Text(item.startDate?.format_DDMMYY_HHmm().toString() ?? '', style: TextStyle(color: textColor)),
                          ),
                        ],
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
        onTap: () {
          // Get.to(
          //   () => PlotDetailScreen(
          //     cropId: item.id?.toInt(),
          //     initialIndex: 0,
          //     cropType: item.type?.toInt() ?? -1,
          //   ),
          // );
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (BuildContext context) => PlotDetailScreen(
                cropId: item.id?.toInt(),
                initialIndex: 0,
                cropType: item.type?.toInt() ?? -1,
              ),
            ),
          );
        });
  }
}
