import 'package:flutter/material.dart';
import 'package:satu/core/entity/Category.dart';
import 'package:satu/core/entity/Goods.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/add_product/component/add_category_list_item.dart';
import 'package:satu/views/add_product/component/app_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: AddProductAppBar(title: 'Товар', actions: actions(),),
      body: Column(
        children: [
          InputField(placeholder: 'Поиск по наименованию и коду товара',
            search: true,
            controller: _searchTextController,
            fieldFocusNode: _searchFocusNode,),
          verticalSpaceTiny,
          Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 8.0),
              child: ListView.builder(
                physics: BouncingScrollPhysics(),
                itemCount: catSize + goodSize,
                itemBuilder: (BuildContext context, int index) {
                  if (index < catSize) {
                    Category category = _categories![index];
                    return AddCategoryListItem(
                      name: category.name,
                      isOdd: index % 2 == 0,
                      key: Key('category_${category.id}'),
                      onPress: () => onCategoryPress(category),
                    );
                  }
                  Good good = _goods![index - catSize];
                  return AddProductListItem(
                    key: Key('product_${good.id}'),
                    ean: good.ean,
                    isOdd: index % 2 == 0,
                    name: good.name,
                    price: good.price,
                    categoryName: _history?.last?.name,
                    onPress: () {
                      onGoodPress(good);
                    } ,
                  );
                },
              ),
            ),
          ),

        ],
      ),
    );
  }

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

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

  List<Widget> actions() {
    return [
      if(_history!.length > 1)
        TextButton(onPressed: () {
          _history!.removeLast();
          navigateCategory(_history!.last.id!);
        }, child: Text('Назад', style: TextStyle(color: Colors.black),),),

      TextButton(onPressed: reset, child: Text('Сбросить', style: TextStyle(color: Colors.black),),)
    ];
  }

  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;
    });
  }

}
