import 'package:farm_tpf/custom_model/LocationUnit.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/screens/location_unit/widget_search.dart';
import 'package:farm_tpf/utils/const_common.dart';
import 'package:farm_tpf/utils/const_string.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import 'bloc/location_bloc.dart';

class LocationScreen extends StatefulWidget {
  final LocationType type;
  final int selectedId;
  final int filterId;
  final String titleName;
  LocationScreen({required this.titleName, required this.type, required this.selectedId, required this.filterId});
  @override
  _LocationScreenState createState() => _LocationScreenState();
}

class _LocationScreenState extends State<LocationScreen> {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => LocationBloc(repository: Repository()),
      child: HoldInfinityWidget(
        type: widget.type,
        selectedId: widget.selectedId,
        filterId: widget.filterId,
        titleName: widget.titleName,
      ),
    );
  }
}

class HoldInfinityWidget extends StatelessWidget {
  final int selectedId;
  final LocationType type;
  final int filterId;
  final String titleName;
  HoldInfinityWidget({required this.selectedId, required this.type, required this.filterId, required this.titleName});
  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),
              ),
            ),
            WidgetSearchLocation(
              filterId: filterId,
              type: type,
              selectedId: selectedId,
            ),
            Expanded(
                child: InfinityView(
              selectedId: selectedId,
              type: type,
              filterId: filterId,
            ))
          ],
        ));
  }
}

class InfinityView extends StatefulWidget {
  final int filterId;
  final int selectedId;
  final LocationType type;
  InfinityView({required this.selectedId, required this.type, required this.filterId});
  @override
  _InfinityViewState createState() => _InfinityViewState();
}

class _InfinityViewState extends State<InfinityView> {
  late LocationBloc _locationBloc;

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

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<LocationBloc, LocationState>(
      builder: (context, state) {
        if (state is LocationFailure) {
          return const Center(child: Text(label_error_get_data));
        }
        if (state is LocationSuccess) {
          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]);
                  },
                  itemCount: state.items.length),
              onRefresh: () async {
                _locationBloc.add(OnRefresh(locationType: widget.type, selectedId: widget.selectedId, filterId: widget.filterId));
              });
        }
        return Center(
          child: LoadingListPage(),
        );
      },
    );
  }

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

class ItemInfinityWidget extends StatelessWidget {
  final LocationUnit item;

  const ItemInfinityWidget({Key? key, required this.item}) : 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: Text("${item.name}"),
              value: item,
              groupValue: item.isSelected == false ? null : item,
              onChanged: (LocationUnit? value) {
                Navigator.of(context).pop(value ?? '');
              }),
        ),
        onTap: () {});
  }
}
