import 'package:farm_tpf/custom_model/action_form/CommonData.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/bloc/common_data_bloc.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';

class CommonDataHelperScreen extends StatefulWidget {
  final String tbSupply;
  final String? condition;
  final int selectedId;
  final String titleName;
  final List<CommonData> currentItems;
  final int currentEditId;
  CommonDataHelperScreen(
      {required this.tbSupply,
      this.condition,
      required this.selectedId,
      required this.titleName,
      required this.currentItems,
      required this.currentEditId});
  @override
  _CommonDataHelperScreenState createState() => _CommonDataHelperScreenState();
}

class _CommonDataHelperScreenState extends State<CommonDataHelperScreen> {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => CommonDataBloc(repository: Repository())
        ..add(
          DataFetched(
            tbSupply: widget.tbSupply,
            condition: widget.condition ?? '',
            selectedId: widget.selectedId,
          ),
        ),
      child: HoldInfinityWidget(
        selectedId: widget.selectedId,
        tbSupply: widget.tbSupply,
        condition: widget.condition,
        titleName: widget.titleName,
        currentItems: widget.currentItems,
        currentEditId: widget.currentEditId,
      ),
    );
  }
}

class HoldInfinityWidget extends StatelessWidget {
  final int selectedId;
  final String tbSupply;
  final String? condition;
  final String titleName;
  final List<CommonData> currentItems;
  final int currentEditId;
  HoldInfinityWidget(
      {required this.selectedId,
      required this.tbSupply,
      this.condition,
      required this.titleName,
      required this.currentItems,
      required this.currentEditId});
  final GlobalKey<ScaffoldState> _scaffoldKey = new 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: TextStyle(fontWeight: FontWeight.w500, fontSize: 22),
              ),
            ),
            Expanded(
                child: InfinityView(
              selectedId: selectedId,
              tbsupply: tbSupply,
              condition: condition,
              currentItems: currentItems,
              currentEditId: currentEditId,
            ))
          ],
        ));
  }
}

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

class _InfinityViewState extends State<InfinityView> {
  CommonDataBloc? _commonDataBloc;

  @override
  void initState() {
    _commonDataBloc = BlocProvider.of<CommonDataBloc>(context);
    _commonDataBloc?.add(DataFetched(tbSupply: widget.tbsupply, condition: widget.condition ?? '', selectedId: widget.selectedId));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<CommonDataBloc, CommonDataState>(
      builder: (context, state) {
        if (state is CommonDataFailure) {
          return Center(child: Text(label_error_get_data));
        }
        if (state is CommonDataSuccess) {
          if ((state.items ?? []).isEmpty) {
            return Center(child: Text(label_list_empty));
          }
          return RefreshIndicator(
              child: ListView.builder(
                itemBuilder: (BuildContext context, int index) {
                  return index >= (state.items?.length ?? 0)
                      ? BottomLoader()
                      : ItemInfinityWidget(
                          item: state.items?[index],
                          currentItems: widget.currentItems,
                          currentEditId: widget.currentEditId,
                        );
                },
                itemCount: state.items?.length ?? 0,
              ),
              onRefresh: () async {
                _commonDataBloc?.add(
                  OnRefresh(
                    tbSupply: widget.tbsupply,
                    condition: widget.condition ?? '',
                    selectedId: widget.selectedId,
                  ),
                );
              });
        }
        return Center(
          child: LoadingListPage(),
        );
      },
    );
  }

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

class ItemInfinityWidget extends StatelessWidget {
  final CommonData item;
  final List<CommonData> 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: BoxDecoration(border: Border(bottom: BorderSide(color: Colors.grey, width: 0.35))),
        child: RadioListTile(
          title: Text(item.name.toString()),
          value: item,
          groupValue: item?.isSelected == true ? item : null,
          onChanged: (CommonData? value) {
            var editedId = (currentEditId > 0) ? currentEditId : -1;
            if (currentItems.map((e) => e.id).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: () {},
    );
  }
}
