import 'package:flutter/material.dart';
import 'package:satu/core/entity/category_entity.dart';
import 'package:satu/core/entity/goods_entity.dart';
import 'package:satu/core/redux/actions/sell_actions.dart';
import 'package:satu/core/redux/store.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/shared/app_colors.dart';
import 'package:satu/shared/ui_helpers.dart';
import 'package:satu/views/work/views/add_product/component/add_category_list_item.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';

import 'component/add_product_list_item.dart';

class AddProductView extends StatefulWidget {
  @override
  _AddProductViewState createState() => _AddProductViewState();
}

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


  List<Category>? _history;
  List<Category>? _categories;
  List<Good>? _goods;


  @override
  void initState() {
    _searchTextController = TextEditingController();
    _searchTextController.addListener(() {
      if(_searchTextController.text.isNotEmpty){
          searchByField(_searchTextController.text);
      } else {
         reset();
      }
    });
    _history = [Category()
      ..id = 0
    ];
    _categories = [];
    _goods = [];
    super.initState();
    navigateCategory(0);
  }

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

  @override
  Widget build(BuildContext context) {
    int catSize = _categories?.length ?? 0;
    int goodSize = _goods?.length ?? 0;
    return Scaffold(
      appBar: ProductsAppBar( title: 'Категория',),
      body: Column(
        children: [
          InputField(placeholder: 'Поиск по наименованию или коду товара',
            search: true,
            controller: _searchTextController,
            fieldFocusNode: _searchFocusNode,),
          verticalSpaceTiny,
          ProductsTitleBarBar(title: goodSize > 0 ? 'Выберите товар' : 'Выберите категорию',),
          Expanded(
            child: ListView.separated(
              physics: BouncingScrollPhysics(),
              itemCount: catSize + goodSize,
              itemBuilder: (BuildContext context, int index) {
                if (index < catSize) {
                  Category category = _categories![index];
                  return AddCategoryListItem(
                    name: category.name,
                    key: Key('category_${category.id}'),
                    onPress: () => onCategoryPress(category),
                  );
                }
                Good good = _goods![index - catSize];
                return AddProductListItem(
                  key: Key('product_${good.id}'),
                  ean: good.ean,
                  name: good.name,
                  price: good.price,
                  categoryName: _history?.last?.name,
                  onPress: () {
                    onGoodPress(good);
                  } ,
                );
              }, separatorBuilder: (BuildContext context, int index) {
                return Divider(height: 1.0, color: disableColor,);
            },
            ),
          ),

        ],
      ),
    );
  }

  void onCategoryPress(Category category) {
    _history!.add(category);
    navigateCategory(category.id!);
  }

  void onGoodPress(Good good) {
    Redux.store!.dispatch(addSellItem(good: good));
    _navigatorService.pop<String>();
  }

  void reset() {
      _history = [Category()
        ..id = 0
      ];
      navigateCategory(0);
      _searchTextController.clear();
    }

  void navigateCategory(int categoryId) async {
    List<Category> categories = await _dictionaryService.getCategoryByParentId(categoryId);
    List<Good> goods = await _dictionaryService.getGoodsByCategoryId(categoryId);
    setState(() {
      _categories = categories;
      _goods = goods;
    });
  }

  void searchByField(String query) async {
    List<Category> categories = [];
    List<Good> goods = await _dictionaryService.getGoodsByNameOrEan(query);
    setState(() {
      _categories = categories;
      _goods = goods;
    });
  }

}
