import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:frezka/components/app_scaffold.dart';
import 'package:frezka/components/loader_widget.dart';
import 'package:frezka/utils/colors.dart';
import 'package:frezka/utils/common_base.dart';
import 'package:nb_utils/nb_utils.dart';

import '../../../components/empty_error_state_widget.dart';
import '../../../main.dart';
import '../../../utils/constants.dart';
import '../../booking/booking_repository.dart';
import '../../booking/model/booking_status_response.dart';
import '../../booking/shimmer/booking_status_list_shimmer.dart';
import '../component/booking_list_component.dart';

class BookingFragment extends StatefulWidget {
  @override
  _BookingFragmentState createState() => _BookingFragmentState();
}

class _BookingFragmentState extends State<BookingFragment> with TickerProviderStateMixin {
  TextEditingController searchBookingCont = TextEditingController();

  FocusNode searchFocusNode = FocusNode();

  TabController? _tabController;

  Future<List<BookingStatusData>>? future;

  @override
  void initState() {
    super.initState();
    init();

    if (bookingStatusListCached != null) {
      _tabController = TabController(length: bookingStatusListCached!.length, vsync: this);
      _tabController!.addListener(() {
        onTabChangeListener();
      });
    }
  }

  void init({bool flag = false}) async {
    future = getBookingStatus(
      tabController: _tabController,
      vsync: this,
      onTabChangeListener: () {
        onTabChangeListener();
      },
    );
    if (flag) setState(() {});
  }

  void onTabChangeListener() {
    if (!_tabController!.indexIsChanging) {
      searchBookingCont.clear();
      setState(() {});
    }
  }

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

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

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
      appBarWidget: PreferredSize(
        preferredSize: Size(context.width(), 100),
        child: Stack(
          clipBehavior: Clip.none,
          alignment: Alignment.bottomCenter,
          children: [
            Container(
              width: context.width(),
              height: 150,
              decoration: boxDecorationWithRoundedCorners(
                borderRadius: BorderRadius.only(bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20)),
                backgroundColor: context.primaryColor,
              ),
              child: appBarWidget(
                locale.booking,
                center: true,
                showBack: false,
                color: context.primaryColor,
                textColor: white,
                textSize: APPBAR_TEXT_SIZE,
              ).cornerRadiusWithClipRRectOnly(bottomLeft: 20, bottomRight: 20),
            ),
            Positioned(
              bottom: -20,
              left: 20,
              right: 20,
              child: AppTextField(
                controller: searchBookingCont,
                textFieldType: TextFieldType.OTHER,
                focus: searchFocusNode,
                suffix: CloseButton(
                  onPressed: () {
                    hideKeyboard(context);
                    searchBookingCont.clear();

                    appStore.setLoading(true);
                    onBookingListUpdate.call(searchBookingCont.text);
                    setState(() {});
                  },
                ).visible(searchBookingCont.text.isNotEmpty),
                onFieldSubmitted: (s) {
                  appStore.setLoading(true);
                  onBookingListUpdate.call(searchBookingCont.text);
                  setState(() {});
                },
                decoration: inputDecoration(context, hint: locale.searchBooking, prefixIcon: Icon(Icons.search, color: textSecondaryColorGlobal)),
              ),
            )
          ],
        ),
      ),
      body: Stack(
        children: [
          FutureBuilder<List<BookingStatusData>>(
            future: future,
            initialData: bookingStatusListCached,
            builder: (context, statusList) {
              if (statusList.hasData) {
                if (statusList.data.validate().isEmpty)
                  return NoDataWidget(
                    title: locale.noBookingsFound,
                    imageWidget: EmptyStateWidget(),
                    onRetry: () {
                      appStore.setLoading(true);

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

                              return Tab(child: Text(statusData.title.validate()));
                            }),
                          ),
                        ),
                      ),
                      TabBarView(
                        controller: _tabController,
                        children: List.generate(statusList.data.validate().length, (index) {
                          return BookingListComponent(bookingStatusData: statusList.data.validate()[index]);
                        }),
                      ).expand(),
                    ],
                  ),
                );
              }

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

                      init(flag: true);
                    },
                  );
                },
              );
            },
          ),
          Observer(builder: (context) => LoaderWidget().visible(appStore.isLoading)),
        ],
      ),
    );
  }
}
