import 'package:didvan/config/design_config.dart';
import 'package:didvan/models/notification_message.dart';
import 'package:didvan/models/view/action_sheet_data.dart';
import 'package:didvan/providers/theme.dart';
import 'package:didvan/services/app_initalizer.dart';
import 'package:didvan/utils/action_sheet.dart';
import 'package:didvan/views/home/explore/explore.dart';
import 'package:didvan/views/home/main/main_page.dart';
import 'package:didvan/views/home/media/media_page.dart';
import 'package:didvan/views/home/home_state.dart';
import 'package:didvan/views/home/new_statistic/new_statistic.dart';
import 'package:didvan/views/home/search/search.dart';
import 'package:didvan/views/ai_section/ai_section_page.dart';
import 'package:didvan/views/widgets/didvan/text.dart';
import 'package:didvan/views/widgets/didvan/bnb.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:flutter_animate/flutter_animate.dart';
import '../../services/app_home_widget/home_widget_repository.dart';

final GlobalKey<ScaffoldState> homeScaffKey = GlobalKey<ScaffoldState>();

class Home extends StatefulWidget {
  final bool? showDialogs;
  const Home({Key? key, this.showDialogs}) : super(key: key);

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home>
    with SingleTickerProviderStateMixin, WidgetsBindingObserver {
  late final TabController _tabController;

  @override
  void initState() {
    final state = context.read<HomeState>();
    DesignConfig.updateSystemUiOverlayStyle();
    _tabController = TabController(length: 5, vsync: this, initialIndex: 0);
    state.tabController = _tabController;

    _tabController.addListener(() {
      if (_tabController.indexIsChanging) {
        state.currentPageIndex = _tabController.index;
      } else {
        state.currentPageIndex = _tabController.index;
      }
    });
    if (!kIsWeb) {
      Future.delayed(Duration.zero, () {
        HomeWidgetRepository.fetchWidget();
        HomeWidgetRepository.decideWhereToGo();
        NotificationMessage? data = HomeWidgetRepository.data;
        if (data != null) {
          HomeWidgetRepository.decideWhereToGoNotif();
        }
        AppInitializer.handleCLick(state, _tabController);
      });
    }
    state.refresh();
    context.read<ThemeProvider>().addListener(() {
      state.refresh();
    });

    super.initState();
  }

  PreferredSizeWidget? getAppBar() {
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: homeScaffKey,
      backgroundColor: Theme.of(context).colorScheme.background,
      resizeToAvoidBottomInset: false,
      drawer: null,
      body: WillPopScope(
        onWillPop: () async {
          if (context.read<HomeState>().tabController.index == 0) {
            if (kIsWeb) {
              return true;
            }
            ActionSheetUtils(context).openDialog(
                data: ActionSheetData(
              content: const DidvanText(
                'آیا قصد خروج از برنامه را دارید؟',
              ),
              onConfirmed: () {
                SystemChannels.platform.invokeMethod('SystemNavigator.pop');
              },
              isBackgroundDropBlur: true,
              confrimTitle: 'بله',
              dismissTitle: 'خیر',
            ));
          } else {
            _tabController.animateTo(0);
          }
          return false;
        },
        child: Consumer<HomeState>(
          builder: (context, state, child) => AnimatedCrossFade(
            duration: DesignConfig.lowAnimationDuration,
            crossFadeState: state.filtering
                ? CrossFadeState.showSecond
                : CrossFadeState.showFirst,
            firstChild: SizedBox(
              height: MediaQuery.of(context).size.height,
              width: MediaQuery.of(context).size.width,
              child: TabBarView(
                physics: const NeverScrollableScrollPhysics(),
                controller: _tabController,
                children: const [
                  MainPage(),
                  MediaPage(),
                  NewStatistic(),
                  ExplorePage(),
                  AiSectionPage(),
                ],
              ),
            ),
            secondChild: const SearchPage(),
          ),
        ),
      ),
      bottomNavigationBar: Consumer<HomeState>(
        builder: (context, state, child) => DidvanBNB(
          currentTabIndex: state.currentPageIndex,
          onTabChanged: (index) {
            if (index < _tabController.length) {
              state.currentPageIndex = index;
              FocusScope.of(context).unfocus();
              state.resetFilters(false);
              _tabController.animateTo(index);
            }
          },
        ),
      )
          .animate()
          .slideY(
            duration: 500.ms,
            begin: 1,
            curve: Curves.easeOut,
          ),
    );
  }
}