import 'dart:async';

import 'package:flutter/material.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:satu/core/models/dictionary/category/category_response.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 CategoryDictionaryView extends StatefulWidget {
  @override
  _CategoryDictionaryViewState createState() => _CategoryDictionaryViewState();
}

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

  static const _pageSize = 20;
  String query = '';
  Timer? _debounce;

  final PagingController<int, CategoryResponse> _pagingController =
      PagingController(firstPageKey: 1);

  @override
  void initState() {
    _searchTextController = TextEditingController();
    _searchTextController.addListener(() {
      setState(() {
        query = _searchTextController.text;
      });
      if (_debounce?.isActive ?? false) _debounce?.cancel();
      _debounce = Timer(const Duration(milliseconds: 500), () {
        _pagingController.refresh();
      });
    });
    _pagingController.addPageRequestListener((pageKey) {
      _fetchData(pageKey, _pageSize, query);
    });
    super.initState();
  }

  @override
  void dispose() {
    _debounce?.cancel();
    _pagingController.dispose();
    _searchTextController.dispose();
    _searchFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: const ProductsAppBar(
        title: 'Категории',
        drawerShow: true,
      ),
      body: Column(
        children: [
          InputField(
            placeholder: 'Поиск по наименованию категории',
            search: true,
            controller: _searchTextController,
            fieldFocusNode: _searchFocusNode,
          ),
          const ProductsTitleBarBar(title: 'Список категории'),
          Expanded(
            child: PagedListView<int, CategoryResponse>.separated(
              physics: const BouncingScrollPhysics(),
              separatorBuilder: (BuildContext context, int index) {
                return const Divider(
                  height: 1.0,
                  color: disableColor,
                );
              },
              pagingController: _pagingController,
              builderDelegate: PagedChildBuilderDelegate<CategoryResponse>(
                itemBuilder: (BuildContext context, CategoryResponse category,
                    int index) {
                  return DictionaryTile(
                    key: Key('category_${category.id}'),
                    onPress: () async {
                      final dynamic result = await _navigatorService
                          .push(categoryEditRoute, arguments: category);
                      if (result != null && true == (result as bool)) {
                        _pagingController.refresh();
                      }
                    },
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          category.name,
                          style:
                              const TextStyle(fontSize: 12, color: textColor),
                        ),
                        Text(
                            category.parentId == null
                                ? 'Корневая категория'
                                : 'Родитель: ${category.parentId}',
                            style: const TextStyle(
                                fontSize: 10, color: placeholderColor)),
                      ],
                    ),
                  );
                },
              ),
            ),
          )
        ],
      ),
      floatingActionButton: FloatingActionButton(
        elevation: 2,
        onPressed: () => _navigatorService.push(categoryEditRoute,
            arguments: CategoryResponse()),
        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 {
    dynamic filter = {'col': 'name', 'action': 'like', 'val': query ?? ''};
    final List<CategoryResponse> newItems = await _dictionaryService
        .getCategories(page: pageKey, filter: filter, perpage: perPage);

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