import 'package:didvan/config/design_config.dart';
import 'package:didvan/config/theme_data.dart';
import 'package:didvan/constants/app_icons.dart';
import 'package:didvan/constants/assets.dart';
import 'package:didvan/main.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/routes/routes.dart';
import 'package:didvan/services/app_initalizer.dart';
import 'package:didvan/utils/action_sheet.dart';
import 'package:didvan/views/ai/ai_state.dart';
import 'package:didvan/views/ai/history_ai_chat_state.dart';
import 'package:didvan/views/ai/widgets/hoshan_drawer.dart';
import 'package:didvan/views/home/categories/categories_page.dart';
import 'package:didvan/views/home/main/main_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/widgets/didvan/text.dart';
import 'package:didvan/views/widgets/hoshan_app_bar.dart';
import 'package:didvan/views/widgets/ink_wrapper.dart';
import 'package:didvan/views/widgets/logo_app_bar.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:flutter_svg/svg.dart';
import 'package:provider/provider.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;

  Future<void> _showDialog(BuildContext context) async {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ActionSheetUtils(context)
          .openDialog(
            data: ActionSheetData(
              hasDismissButton: false,
              hasConfirmButton: false,
              withoutButtonMode: true,
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      InkWrapper(
                        onPressed: () => Navigator.of(context).pop(),
                        child: const Icon(DidvanIcons.close_solid, size: 24),
                      ),
                    ],
                  ),
                  const SizedBox(height: 15),
                  SvgPicture.asset(Assets.horizontalLogoWithText, height: 80),
                  const SizedBox(height: 24),
                  DidvanText(
                    'به سوپر اپلیکیشن دیدوان خوش آمدید',
                    textAlign: TextAlign.center,
                    style: Theme.of(context).textTheme.titleMedium,
                  ),
                  const SizedBox(height: 24),
                ],
              ),
            ),
          )
          .then((value) => ActionSheetUtils(context).openDialog(
                data: ActionSheetData(
                  // ignore: deprecated_member_use
                  backgroundColor: Theme.of(context).colorScheme.background,
                  isBackgroundDropBlur: true,
                  content: Stack(
                    children: [
                      Padding(
                        padding: const EdgeInsets.only(top: 24.0),
                        child: Column(
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                DidvanText(
                                  'شخصی سازی محتوا',
                                  style:
                                      Theme.of(context).textTheme.displaySmall,
                                  color: Theme.of(context).colorScheme.text,
                                ),
                              ],
                            ),
                            const SizedBox(
                              height: 12,
                            ),
                            const DidvanText(
                                "کاربر گرامی\nلطفا جهت شخصی‌سازی و استفاده بهتر از برنامه، دسته‌بندی‌های مورد علاقه خود و زمان دریافت اعلانات را انتخاب نمایید.")
                          ],
                        ),
                      ),
                      Positioned(
                        top: 0,
                        left: 0,
                        child: InkWrapper(
                          onPressed: () {
                            Future.delayed(
                              Duration.zero,
                              () => Navigator.of(context).pop(),
                            );
                          },
                          child: const Icon(
                            DidvanIcons.close_solid,
                            size: 24,
                          ),
                        ),
                      ),
                    ],
                  ),
                  onConfirmed: () {
                    Future.delayed(
                      Duration.zero,
                      () =>
                          Navigator.of(navigatorKey.currentContext!).pushNamed(
                        Routes.favouritesStep,
                        arguments: {"toTimer": true},
                      ),
                    );
                  },
                  confrimTitle: 'تایید',
                ),
              ));
    });
  }

  @override
  void initState() {
    if (widget.showDialogs ?? false) {
      _showDialog(context);
    }

    final state = context.read<HomeState>();
    DesignConfig.updateSystemUiOverlayStyle();
    _tabController = TabController(length: 4, vsync: this, initialIndex: 0);
    state.tabController = _tabController;
    
    // این قسمت را اضافه یا جایگزین کنید
    _tabController.addListener(() {
      state.currentPageIndex = _tabController.index;
      if (_tabController.index == 2) {
        // با هر بار ورود به تب هوشان، لیست چت‌ها ریست می‌شود
        final historyState = context.read<HistoryAiChatState>();
        historyState.chats.clear();
        historyState.archivedChats.clear();
        historyState.update(); // برای اطمینان از به‌روزرسانی UI
        historyState.getBots();
      }
    });
    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() {
    PreferredSizeWidget result = const LogoAppBar();
    if (context.watch<HomeState>().tabController.index == 2) {
      result = HoshanAppBar(
        onBack: () {
          final state = context.read<AiState>();
          if (state.page == 1) {
            state.goToAi();
          }
        },
      );
    }

    return result;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: homeScaffKey,
      appBar: getAppBar(),
      resizeToAvoidBottomInset: false,
      drawer: context.watch<HomeState>().tabController.index == 2
          ? HoshanDrawer(
              scaffKey: homeScaffKey,
            )
          : null,
      // ignore: deprecated_member_use
      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 if (context.read<HomeState>().tabController.index == 2) {
            switch (context.read<AiState>().page) {
              case 1:
                context.read<AiState>().goToAi();
                break;

              default:
                _tabController.animateTo(0);
            }
          } 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(),
                  CategoriesPage(),
                  NewStatistic(),
                ],
              ),
            ),
            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);
            }
          },
        ),
      ),
    );
  }
}
