import 'package:farm_tpf/custom_model/SuppliesUsing.dart';
import 'package:farm_tpf/custom_model/Supply.dart';
import 'package:farm_tpf/data/repository/repository.dart';
import 'package:farm_tpf/presentation/custom_widgets/app_bar_widget.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/custom_widgets/widget_utils.dart';
import 'package:farm_tpf/presentation/screens/resources/bloc/supply_bloc.dart';
import 'package:farm_tpf/presentation/screens/resources/widget_search.dart';
import 'package:farm_tpf/utils/const_string.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:get/get.dart';
import 'package:farm_tpf/utils/formatter.dart';

class ResourceHelperScreen extends StatefulWidget {
  final String type;
  final int selectedId;
  final String titleName;
  final List<SuppliesUsing> currentItems;
  final int currentEditId;
  ResourceHelperScreen(
      {required this.type, required this.selectedId, required this.titleName, required this.currentItems, required this.currentEditId});
  @override
  _ResourceHelperScreenState createState() => _ResourceHelperScreenState();
}

class _ResourceHelperScreenState extends State<ResourceHelperScreen> {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => SupplyBloc(repository: Repository())..add(DataFetched(type: widget.type, selectedId: widget.selectedId)),
      child: HoldInfinityWidget(
        selectedId: widget.selectedId,
        type: widget.type,
        titleName: widget.titleName,
        currentItems: widget.currentItems,
        currentEditId: widget.currentEditId,
      ),
    );
  }
}

class HoldInfinityWidget extends StatelessWidget {
  final int selectedId;
  final String type;
  final String titleName;
  final List<SuppliesUsing> currentItems;
  final int currentEditId;
  HoldInfinityWidget(
      {required this.selectedId, required this.type, required this.titleName, required this.currentItems, required this.currentEditId});
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        key: _scaffoldKey,
        appBar: AppBarWidget(),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                '$titleName',
                style: const TextStyle(fontWeight: FontWeight.w500, fontSize: 22),
              ),
            ),
            WidgetSearch(
              type: type,
              selectedId: selectedId,
            ),
            Expanded(
                child: InfinityView(
              selectedId: selectedId,
              type: type,
              currentItems: currentItems,
              currentEditId: currentEditId,
            ))
          ],
        ));
  }
}

class InfinityView extends StatefulWidget {
  final int selectedId;
  final String type;
  final List<SuppliesUsing> currentItems;
  final int currentEditId;
  InfinityView({required this.selectedId, required this.type, required this.currentItems, required this.currentEditId});
  @override
  _InfinityViewState createState() => _InfinityViewState();
}

class _InfinityViewState extends State<InfinityView> {
  late SupplyBloc _supplyBloc;

  @override
  void initState() {
    _supplyBloc = BlocProvider.of<SupplyBloc>(context);
    _supplyBloc.add(DataFetched(type: widget.type, selectedId: widget.selectedId));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<SupplyBloc, SupplyState>(
      builder: (context, state) {
        if (state is SupplyFailure) {
          return const Center(child: Text(label_error_get_data));
        }
        if (state is SupplySuccess) {
          if (state.items.isEmpty) {
            return const Center(child: Text(label_list_empty));
          }
          return RefreshIndicator(
              child: ListView.builder(
                  itemBuilder: (BuildContext context, int index) {
                    return index >= state.items.length
                        ? BottomLoader()
                        : ItemInfinityWidget(
                            item: state.items[index],
                            currentItems: widget.currentItems,
                            currentEditId: widget.currentEditId,
                          );
                  },
                  itemCount: state.items.length),
              onRefresh: () async {
                _supplyBloc.add(OnRefresh(type: widget.type, selectedId: widget.selectedId));
              });
        }
        return Center(
          child: LoadingListPage(),
        );
      },
    );
  }

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

class ItemInfinityWidget extends StatelessWidget {
  final Supply item;
  final List<SuppliesUsing> currentItems;
  final int currentEditId;

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

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        child: Container(
            decoration: const BoxDecoration(border: Border(bottom: BorderSide(color: Colors.grey, width: 0.35))),
            child: RadioListTile(
                title: Row(
                  children: [
                    Expanded(child: Text(item.tbSuppliesName.toString())),
                    Text("${item.quantity?.formatNumtoStringDecimal()} ${item.unit}")
                  ],
                ),
                subtitle: Text(item.tbWarehouseName.toString()),
                value: item,
                groupValue: item.isSelected == false ? null : item,
                onChanged: (Supply? value) {
                  if ((value?.quantity ?? 0) <= 0) {
                    Utils.showSnackBarWarning(message: "Vật tư đã hết");
                  } else {
                    var editedId = (currentEditId > 0) ? currentEditId : -1;
                    if (currentItems.map((e) => e.tbSuppliesInWarehouseId).contains(item.id) && item.id != editedId) {
                      Utils.showSnackBarWarning(message: "Vật tư đã được thêm, vui lòng chọn vật tư khác");
                    } else {
                      //close nackbar if open
                      if (Get.isSnackbarOpen) Get.back();
                      Navigator.of(context).pop(value);
                    }
                  }
                })),
        onTap: () {});
  }
}
