import 'package:flutter/material.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:satu/core/models/dictionary/contragent/contragent_response_entity.dart';
import 'package:satu/core/services/dictionary_service.dart';
import 'package:satu/core/services/navigator_service.dart';
import 'package:satu/core/utils/locator.dart';
import 'package:satu/routes/route_names.dart';
import 'package:satu/shared/app_colors.dart';
import 'package:satu/views/dictionaries/component/dictionary_list_tile.dart';
import 'package:satu/widgets/bar/products_app_bar.dart';
import 'package:satu/widgets/bar/products_title_bar.dart';
import 'package:satu/widgets/fields/input_field.dart';

class ContragentsDictionaryView extends StatefulWidget {
  @override
  _ContragentsDictionaryViewState createState() =>
      _ContragentsDictionaryViewState();
}

class _ContragentsDictionaryViewState extends State<ContragentsDictionaryView> {
  final DictionaryService _dictionaryService = locator<DictionaryService>();
  final NavigatorService _navigatorService = locator<NavigatorService>();
  late TextEditingController _searchTextController;
  final FocusNode _searchFocusNode = FocusNode();

  late List<ContragentResponseEntity> items = [];
  static const _pageSize = 20;

  final PagingController<int, ContragentResponseEntity> _pagingController =
      PagingController(firstPageKey: 0);

  @override
  void initState() {
    _searchTextController = TextEditingController();
    _searchTextController.addListener(() {
      if (_searchTextController.text.isNotEmpty) {
        //searchByField(_searchTextController.text);
      } else {
        reset();
      }
    });
    _pagingController.addPageRequestListener((pageKey) {
      _fetchData(pageKey, _pageSize, null);
    });
    super.initState();
  }

  Future<void> initQuery() async {
    //searchByField('');
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: ProductsAppBar(
        title: 'Контрагенты',
        drawerShow: true,
      ),
      body: Column(
        children: [
          InputField(
            placeholder: 'Поиск по наименованию',
            search: true,
            controller: _searchTextController,
            fieldFocusNode: _searchFocusNode,
          ),
          const ProductsTitleBarBar(title: 'Список контрагентов'),
          Expanded(
              child: PagedListView<int, ContragentResponseEntity>(
            pagingController: _pagingController,
            builderDelegate:
                PagedChildBuilderDelegate<ContragentResponseEntity>(
              itemBuilder: (BuildContext context,
                  ContragentResponseEntity entity, int index) {
                return DictionaryTile(
                  key: Key('contragent_${entity.id}'),
                  onPress: () async {
                    final dynamic result = await _navigatorService
                        .push(contragentEditRoute, arguments: entity);
                    if (result != null && true == (result as bool)) {
                      _pagingController.refresh();
                    }
                  },
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        entity.name ?? '',
                        style: const TextStyle(fontSize: 12, color: textColor),
                      ),
                      Text('БИН/ИИН: ${entity.biniin}',
                          style: const TextStyle(
                              fontSize: 10, color: placeholderColor)),
                    ],
                  ),
                );
              },
            ),
          ))
        ],
      ),
      floatingActionButton: FloatingActionButton(
        elevation: 2,
        onPressed: () => locator<NavigatorService>().push(contragentEditRoute,
            arguments: ContragentResponseEntity()..refAppCompanyTypeId = 5),
        child: const Icon(
          Icons.add_rounded,
          size: 34.0,
          color: whiteColor,
        ),
      ),
    );
  }

  void reset() {
    _searchTextController.clear();
  }

  Future<void> _fetchData(int pageKey, int perPage, String? query) async {
    final List<ContragentResponseEntity> newItems = await _dictionaryService
        .getContragents(page: pageKey, query: query, perpage: perPage);

    final isLastPage = newItems.length < _pageSize;
    if (isLastPage) {
      _pagingController.appendLastPage(newItems);
    } else {
      final nextPageKey = pageKey + newItems.length;
      _pagingController.appendPage(newItems, nextPageKey);
    }
  }
}
