// ignore_for_file: deprecated_member_use, deprecated_member_use_from_same_package

import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hoshan/core/services/ad/tapsell_service.dart';
import 'package:hoshan/data/model/home_args.dart';
import 'package:hoshan/data/model/home_navbar_model.dart';
import 'package:hoshan/data/storage/shared_preferences_helper.dart';
import 'package:hoshan/ui/screens/main/assistant/assistant_screen.dart';
import 'package:hoshan/ui/screens/main/home/home_screen.dart';
import 'package:hoshan/ui/screens/main/generate_media_screen.dart';
import 'package:hoshan/ui/screens/main/persons/persons_screen.dart';
import 'package:hoshan/ui/screens/setting/setting_page.dart';
import 'package:hoshan/ui/screens/splash/cubit/user_info_cubit.dart';
import 'package:hoshan/ui/theme/colors.dart';
import 'package:hoshan/ui/theme/cubit/theme_mode_cubit.dart';
import 'package:hoshan/ui/theme/responsive.dart';
import 'package:hoshan/ui/theme/text.dart';
import 'package:hoshan/ui/widgets/components/dialog/dialog_handler.dart';
import 'package:hoshan/ui/widgets/sections/header/home_appbar.dart';
import 'package:share_plus/share_plus.dart';

ValueNotifier<int> screenIndex = ValueNotifier(0);
final searchFocus = FocusNode();

class HomePage extends StatefulWidget {
  final HomeArgs? args;
  const HomePage({super.key, this.args});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  ValueNotifier<bool> visibleAttach = ValueNotifier(false);
  ValueNotifier<bool> visibleRecorder = ValueNotifier(false);

  final List<HomeNavbar> navIcons = [
    HomeNavbar(title: 'خانه', icon: 'home', enabled: true),
    HomeNavbar(title: 'دستیارها', icon: 'assistant', enabled: false),
    HomeNavbar(title: 'مدیا', icon: 'media', enabled: false),
    HomeNavbar(title: 'شخصیت‌ها', icon: 'characters', enabled: false),
    HomeNavbar(title: 'تنظیمات', icon: 'setting', enabled: false),
  ];

  final TextEditingController message = TextEditingController();

  PreferredSizeWidget? getAppBAr(int indexed) {
    PreferredSizeWidget? preferredSizeWidget;
    if (indexed != 1) {
      preferredSizeWidget = HomeAppbar(
        context,
      );
    }
    return preferredSizeWidget;
  }

  @override
  void initState() {
    super.initState();
    // if (!kIsWeb) {
    //   try {
    //     final ad = AdiveryService();
    //     ad.showInterstitial();
    //   } catch (e) {
    //     if (kDebugMode) {
    //       print('Error initializing Adivery: $e');
    //     }
    //   }
    // }
    screenIndex.value = 0;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (widget.args != null) {
        if (widget.args!.message != null) {
          DialogHandler(context: context)
              .showWellcome(mesasge: widget.args!.message!);
        }
        final iso = InvitePopupStorage.getLastTime();
        final now = DateTime.now();
        final nowId = int.parse(
            '${now.year}${now.month.toString().padLeft(2, '0')}${now.day.toString().padLeft(2, '0')}');
        int? dateId;
        try {
          final date = DateTime.parse(iso);

          dateId = int.parse(
              '${date.year}${date.month.toString().padLeft(2, '0')}${date.day.toString().padLeft(2, '0')}');
        } catch (e) {
          if (kDebugMode) {
            print('Error when show heart: $e');
          }
        }
        if (dateId != nowId && Random().nextBool()) {
          DialogHandler(context: context).showHeart(
            onConfirm: () async {
              try {
                await Share.share('هوشان؛ دوست هوش مصنوعی تو\n'
                    'هر سوالی داری، هر تصمیمی که می‌خوای بگیری یا هر ایده‌ی خلاقانه‌ای که داری و می‌خوای به واقعیت تبدیلش کنی، هوشان همیشه هست تا کمکت کنه!\n'
                    'کد معرف: ${UserInfoCubit.userInfoModel.code}\n'
                    'https://houshan.ai/');
              } catch (e) {
                if (kDebugMode) {
                  print('Error in share Text: $e');
                }
              }
            },
          );
          InvitePopupStorage.setLastTime(now.toIso8601String());
        }
      }
      TapsellService.showAdBanner(context);
    });
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
        valueListenable: screenIndex,
        builder: (context, indexed, _) {
          return WillPopScope(
            onWillPop: () async {
              if (indexed == 0) {
                // if (HomeCubit.chatId.value != null) {
                //   HomeCubit.chatId.value = null;
                //   HomeCubit.bot.value = null;
                //   context.read<HomeCubit>().clearItems();
                //   ChatbotRepository.cancelToken?.cancel();
                //   return false;
                // } else {
                final exit = DialogHandler(context: context).showExit();
                return exit;
                // }
              } else {
                screenIndex.value = 0;
                // mainPageController.jumpToPage(screenIndex.value);

                return false;
              }
            },
            child: Scaffold(
              resizeToAvoidBottomInset: indexed == 0,
              appBar: HomeAppbar(
                context,
              ),
              body: Responsive(context).builder(
                mobile: mainIndexed(indexed),
                desktop: Row(
                  children: [
                    Expanded(
                      flex: 3,
                      child: mainIndexed(indexed),
                    ),
                    Expanded(child: drawerNavigationBar()),
                  ],
                ),
              ),
              bottomNavigationBar: Responsive(context).isMobile()
                  ? homeBottomNavigationBar()
                  : null,
            ),
          );
        });
  }

  Widget mainIndexed(int indexed) {
    return IndexedStack(
      index: indexed,
      children: const [
        HomeScreen(),
        AssistantScreen(),
        GenerateMediaScreen(),
        PersonsScreen(),
        SettingPage(),
      ],
    );
  }

  Widget homeBottomNavigationBar() {
    return ValueListenableBuilder(
        valueListenable: screenIndex,
        builder: (context, indexed, _) {
          for (var element in navIcons) {
            element.setEnabled(false);
          }
          navIcons[indexed].setEnabled(true);
          return Directionality(
            textDirection: TextDirection.rtl,
            child: Container(
              margin: const EdgeInsets.fromLTRB(16, 0, 16, 24),
              padding: const EdgeInsets.all(18),
              decoration: BoxDecoration(
                  color: Theme.of(context).colorScheme.surface,
                  borderRadius: BorderRadius.circular(20),
                  boxShadow: [
                    BoxShadow(
                      color: const Color(0xFF000000).withOpacity(0.10),
                      offset: const Offset(0, 20),
                      blurRadius: 46,
                      spreadRadius: 0,
                    ),
                  ]),
              child: Row(
                children: List.generate(navIcons.length, (index) {
                  final navIcon = navIcons[index];

                  return Expanded(
                    child: InkWell(
                        borderRadius: BorderRadius.circular(100),
                        onTap: () async {
                          if (index == indexed) return;
                          screenIndex.value = index;
                          // mainPageController.jumpToPage(index);
                        },
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            navIcon.getIcon(context).svg(
                                color: index == indexed
                                    ? null
                                    : Theme.of(context).colorScheme.onSurface),
                            if (navIcon.enabled)
                              Text(
                                navIcon.title,
                                style: AppTextStyles.body6.copyWith(
                                    color: navIcon.enabled
                                        ? context
                                                    .read<ThemeModeCubit>()
                                                    .state ==
                                                ThemeMode.dark
                                            ? Colors.white
                                            : AppColors.primaryColor[800]
                                        : AppColors.gray.defaultShade),
                              )
                          ],
                        )),
                  );
                }),
              ),
            ),
          );
        });
  }

  Widget drawerNavigationBar() {
    return ValueListenableBuilder(
        valueListenable: screenIndex,
        builder: (context, indexed, _) {
          for (var element in navIcons) {
            element.setEnabled(false);
          }
          navIcons[indexed].setEnabled(true);
          return Directionality(
            textDirection: TextDirection.rtl,
            child: Container(
              padding: const EdgeInsets.all(18),
              decoration: BoxDecoration(
                  color: Theme.of(context).colorScheme.surface,
                  boxShadow: [
                    BoxShadow(
                      color: const Color(0xFF000000).withOpacity(0.10),
                      offset: const Offset(0, 20),
                      blurRadius: 46,
                      spreadRadius: 0,
                    ),
                  ]),
              child: Padding(
                padding: EdgeInsets.only(
                    top: indexed == 1
                        ? kToolbarHeight +
                            (Responsive(context).isMobile() ? 12 : 32)
                        : 0),
                child: Column(
                  children: List.generate(navIcons.length, (index) {
                    final navIcon = navIcons[index];

                    return Column(
                      children: [
                        InkWell(
                          borderRadius: BorderRadius.circular(100),
                          onTap: () {
                            if (index == indexed) return;
                            screenIndex.value = index;
                            // mainPageController.jumpToPage(index);
                          },
                          child: ListTile(
                            leading: navIcon.getIcon(context).svg(
                                width: 32,
                                height: 32,
                                color: index == indexed
                                    ? null
                                    : navIcon.enabled
                                        ? Theme.of(context)
                                            .colorScheme
                                            .onSurface
                                        : AppColors.gray[700]),
                            title: Text(
                              navIcon.title,
                              style: AppTextStyles.headline5.copyWith(
                                  color: navIcon.enabled
                                      ? context.read<ThemeModeCubit>().isDark()
                                          ? Theme.of(context)
                                              .colorScheme
                                              .onSurface
                                          : AppColors.primaryColor[800]
                                      : AppColors.gray[700]),
                            ),
                          ),
                        ),
                        if (index != navIcons.length - 1) const Divider()
                      ],
                    );
                  }),
                ),
              ),
            ),
          );
        });
  }
}
