import 'package:flutter/material.dart';
import 'package:frezka/components/app_scaffold.dart';
import 'package:frezka/components/loader_widget.dart';
import 'package:frezka/screens/order/order_repository.dart';
import 'package:nb_utils/nb_utils.dart';

import '../../../components/empty_error_state_widget.dart';
import '../../../main.dart';
import '../../../utils/app_common.dart';
import '../../../utils/colors.dart';
import '../../../utils/common_base.dart';
import '../component/order_list_component.dart';
import '../model/order_status_response.dart';

class OrderListScreen extends StatefulWidget {
  @override
  _OrderListScreenState createState() => _OrderListScreenState();
}

class _OrderListScreenState extends State<OrderListScreen> {
  TextEditingController searchProductCont = TextEditingController();

  FocusNode searchFocusNode = FocusNode();

  TabController? _orderStatusTabController;

  Future<List<OrderStatusData>>? future;

  @override
  void initState({bool flag = false}) {
    super.initState();
    init();
  }

  void init({bool flag = false}) async {
    future = getOrderStatus(
      tabController: _orderStatusTabController,
      onTabChangeListener: () {
        onTabChangeListener();
      },
    );
    if (flag) setState(() {});
  }

  void onTabChangeListener() {
    if (!_orderStatusTabController!.indexIsChanging) {
      searchProductCont.clear();
      setState(() {});
    }
  }

  @override
  void setState(fn) {
    if (mounted) super.setState(fn);
  }

  @override
  void dispose() {
    _orderStatusTabController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
      appBarWidget: commonAppBarWidget(
        context,
        title: locale.orders, //TODO: string
        appBarHeight: 70,
        showLeadingIcon: true,
        roundCornerShape: true,
      ),
      body: FutureBuilder<List<OrderStatusData>>(
        future: future,
        initialData: orderStatusListCached,
        builder: (context, orderStatusList) {
          if (orderStatusList.hasData) {
            if (orderStatusList.data.validate().isEmpty)
              return NoDataWidget(
                title: locale.noOrdersFound, //TODO: string
                imageWidget: EmptyStateWidget(),
                onRetry: () {
                  appStore.setLoading(true);

                  init(flag: true);
                },
              );
            return DefaultTabController(
              length: orderStatusList.data.validate().length,
              child: Column(
                children: [
                  Container(
                    margin: EdgeInsets.only(top: 30),
                    padding: EdgeInsets.symmetric(horizontal: 16),
                    decoration: boxDecorationDefault(borderRadius: radius(8), color: context.scaffoldBackgroundColor),
                    child: Theme(
                      data: ThemeData(dividerColor: Colors.transparent),
                      child: TabBar(
                        controller: _orderStatusTabController,
                        unselectedLabelStyle: primaryTextStyle(size: 14),
                        labelColor: white,
                        unselectedLabelColor: appStore.isDarkMode ? white : black,
                        labelStyle: boldTextStyle(size: 14),
                        isScrollable: true,
                        indicatorSize: TabBarIndicatorSize.tab,
                        indicator: boxDecorationDefault(color: primaryColor),
                        onTap: (value) {
                          hideKeyboard(context);
                        },
                        tabs: List.generate(orderStatusList.data.validate().length, (index) {
                          OrderStatusData statusData = orderStatusList.data.validate()[index];

                          return Tab(child: Text(getOrderBookingStatus(status: statusData.name.validate())));
                        }),
                      ),
                    ),
                  ),
                  TabBarView(
                    controller: _orderStatusTabController,
                    children: List.generate(orderStatusList.data.validate().length, (index) {
                      return OrderListComponent(orderStatusData: orderStatusList.data.validate()[index]);
                    }),
                  ).expand(),
                ],
              ),
            );
          }

          return snapWidgetHelper(
            orderStatusList,
            loadingWidget: LoaderWidget(),
            errorBuilder: (error) {
              return NoDataWidget(
                title: error,
                imageWidget: ErrorStateWidget(),
                retryText: locale.reload,
                onRetry: () {
                  appStore.setLoading(true);

                  init(flag: true);
                },
              );
            },
          );
        },
      ),
    );
  }
}
