import 'package:aman_kassa_flutter/core/entity/Category.dart';
import 'package:aman_kassa_flutter/core/entity/Goods.dart';
import 'package:aman_kassa_flutter/core/entity/Service.dart';
import 'package:aman_kassa_flutter/core/locator.dart';
import 'package:aman_kassa_flutter/core/services/dialog_service.dart';
import 'package:aman_kassa_flutter/redux/actions/kassa_actions.dart';
import 'package:aman_kassa_flutter/redux/actions/setting_actions.dart';
import 'package:aman_kassa_flutter/redux/constants/setting_const.dart';
import 'package:aman_kassa_flutter/redux/state/kassa_state.dart';
import 'package:aman_kassa_flutter/redux/state/setting_state.dart';
import 'package:aman_kassa_flutter/redux/store.dart';
import 'package:aman_kassa_flutter/shared/app_colors.dart';
import 'package:aman_kassa_flutter/shared/shared_styles.dart';
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';

class CatalogBottomSheet extends StatelessWidget {
  final ScrollController? scrollController;

  CatalogBottomSheet({this.scrollController});

  @override
  Widget build(BuildContext context) {
    return StoreConnector<AppState, KassaState>(
      converter: (store) => store.state.kassaState!,
      onInit: (store) => Redux.store!.dispatch(selectBottomElement(0)),
      builder: (context, vm) {
        return WillPopScope(
          onWillPop: () {
            if (vm.prevCategories!.length > 0) {
              Redux.store!.dispatch(backBottomElement);
            } else
              Navigator.pop(context);
            return new Future(() => false);
          },
          child: Scaffold(
              appBar: AppBar(
                title: Text(
                  vm.prevCategories!.isNotEmpty
                      ? vm.prevCategories!.last.name
                      : '',
                  style: TextStyle(color: Colors.black45),
                ),
                iconTheme: IconThemeData(color: Colors.black),
                backgroundColor: whiteColor,
                elevation: 1,
                leading: IconButton(
                  icon: Icon(vm.prevCategories!.length > 0
                      ? Icons.arrow_back
                      : Icons.close),
                  onPressed: () {
                    if (vm.prevCategories!.length > 0) {
                      Redux.store!.dispatch(backBottomElement);
                    } else
                      Navigator.pop(context);
                  },
                ),
                actions: <Widget>[buildActionContainer()],
              ),
              body: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  Expanded(
                    child: ListView.builder(
                      controller: scrollController,
                      itemCount: vm.bottomSheetElements!.length,
                      itemBuilder: (context, index) {
                        var el = vm.bottomSheetElements![index];
                        String? name;
                        String? price;
                        if (el is Category) {
                          Category category = el;
                          name = category.name;
                        } else if (el is Good) {
                          Good good = el;
                          name = good.name;
                          price = good.price.toString();
                        } else if (el is Service) {
                          Service service = el;
                          name = service.name;
                          price = service.price.toString();
                        }
                        return Card(
                          child: ListTile(
                            leading: el is Category
                                ? Icon(Icons.layers, size: 25)
                                : null,
                            title: Text(
                              name ?? '',
                              style: TextStyle(fontSize: 15),
                            ),
                            onTap: () async {
                              if (el is Category) {
                                Redux.store!
                                    .dispatch(selectBottomElement(el.id!));
                              } else if (el is Good) {
                                await Redux.store!
                                    .dispatch(addProductToKassaItems(el, null));
                                Navigator.pop(context);
                              } else if (el is Service) {
                                await Redux.store!
                                    .dispatch(addServiceToKassaItems(el));
                                Navigator.pop(context);
                              }
                            },
                            trailing: el is Category
                                ? Icon(Icons.chevron_right)
                                : Text(
                                    price ?? '',
                                    style: TextStyle(
                                        fontSize: 15, color: Colors.black54),
                                  ),
                          ),
                        );
                      },
                    ),
                  ),
                  ElevatedButton(
                      child: Text(
                        'Отмена',
                        style: buttonBigTitleTextStyle,
                      ),
                      style: ElevatedButton.styleFrom(backgroundColor: redColor),
                      onPressed: () {
                        Navigator.pop(context);
                      }),
                ],
              )),
        );
      },
    );
  }

  Container buildActionContainer() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 5.0),
      child: StoreConnector<AppState, KassaState>(
          converter: (store) => store.state.kassaState!,
          builder: (_, mainState) {
            return StoreConnector<AppState, SettingState>(
                converter: (store) => store.state.settingState!,
                builder: (_, settingState) {
                  if (mainState.kassaItems!.isNotEmpty) {
                    return GestureDetector(
                        onTap: () {
                          locator<DialogService>().showDialog(
                              description:
                                  'Выбрать другой тип продажи, возможно только при пустом списке покупок');
                        },
                        child: Container(
                          child: Text(
                            settingState.tradeType == SettingTradeTypeGood
                                ? 'Товары'
                                : 'Услуги',
                            style: dropDownTradeTypeTextStyle,
                          ),
                          padding: const EdgeInsets.symmetric(vertical: 8.0),
                        ));
                  }
                  return DropdownButton<String>(
                    value: settingState.tradeType,
                    icon: Icon(
                      Icons.arrow_drop_down_circle,
                      color: yellowColor,
                    ),
                    iconSize: 24,
                    elevation: 6,
                    style: dropDownTradeTypeTextStyle,
                    underline: Container(
                      height: 1,
                    ),
                    onChanged: (String? newValue) {
                      onChangeTradeType(newValue!, settingState.tradeType!);
                    },
                    items: [
                      DropdownMenuItem<String>(
                        child: Text('Товары'),
                        value: SettingTradeTypeGood,
                      ),
                      DropdownMenuItem<String>(
                        child: Text('Услуги'),
                        value: SettingTradeTypeService,
                      )
                    ],
                  );
                });
          }),
    );
  }

  void onChangeTradeType(String newValue, String oldValue) async {
    if (oldValue != newValue) {
      await Redux.store!.dispatch(changeTradeTypeFromSetting(newValue));
      await Redux.store!.dispatch(selectBottomElement(0));
    }
  }
}
