// ignore_for_file: use_build_context_synchronously

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:hoshan/core/utils/date_time.dart';
import 'package:hoshan/data/model/ai/messages_model.dart';
import 'package:hoshan/data/model/ai/send_message_model.dart';
import 'package:hoshan/data/model/assistant_personal_info_model.dart';
import 'package:hoshan/data/model/chat_args.dart';
import 'package:hoshan/data/model/home_args.dart';
import 'package:hoshan/data/model/purchase_args.dart';
import 'package:hoshan/data/model/tools_categories_model.dart';
import 'package:hoshan/data/storage/shared_preferences_helper.dart';
import 'package:hoshan/main.dart';
import 'package:hoshan/ui/screens/assistant/assistant_page.dart';
import 'package:hoshan/ui/screens/assistant/bloc/assistant_info_bloc.dart';
import 'package:hoshan/ui/screens/assistant/bloc/same_assistants_bloc.dart';
import 'package:hoshan/ui/screens/assistant/cubit/assistant_comments_cubit.dart';
import 'package:hoshan/ui/screens/auth/auth_page.dart';
import 'package:hoshan/ui/screens/auth/cubit/auth_screens_cubit.dart';
import 'package:hoshan/ui/screens/auth/gift/gift_credit_screen.dart';
import 'package:hoshan/ui/screens/chat/bloc/messages_bloc.dart';
import 'package:hoshan/ui/screens/chat/bloc/related_questions_bloc.dart';
import 'package:hoshan/ui/screens/chat/chat_page.dart';
import 'package:hoshan/ui/screens/chat/cubit/receive_message_cubit.dart';
import 'package:hoshan/ui/screens/cmp/cmp_page.dart';
import 'package:hoshan/ui/screens/faq/faq_page.dart';
import 'package:hoshan/ui/screens/gmedia/cubit/media_g_response_cubit.dart';
import 'package:hoshan/ui/screens/gmedia/cubit/single_media_cubit.dart';
import 'package:hoshan/ui/screens/gmedia/generators/generate_audio_page.dart';
import 'package:hoshan/ui/screens/gmedia/generators/generate_photo_page.dart';
import 'package:hoshan/ui/screens/gmedia/generators/generate_video_page.dart';
import 'package:hoshan/ui/screens/gmedia/chats/photo_chat_page.dart';
import 'package:hoshan/ui/screens/main/assistant/bloc/create_assistant_bloc.dart';
import 'package:hoshan/ui/screens/main/assistant/create_assistant_page.dart';
import 'package:hoshan/ui/screens/main/assistant/cubit/delete_assistant_cubit.dart';
import 'package:hoshan/ui/screens/main/home/bloc/courses_bloc.dart';
import 'package:hoshan/ui/screens/main/home/cubit/banners_cubit.dart';
import 'package:hoshan/ui/screens/main/home/cubit/best_assistants_cubit.dart';
import 'package:hoshan/ui/screens/main/forum/cubit/comments_cubit.dart';
import 'package:hoshan/ui/screens/main/home_page.dart';
import 'package:hoshan/ui/screens/purchase_page/bloc/plans_bloc.dart';
import 'package:hoshan/ui/screens/purchase_page/purchase_page.dart';
import 'package:hoshan/ui/screens/setting/bloc/report_of_use_bloc.dart';
import 'package:hoshan/ui/screens/setting/cubit/check_username_cubit.dart';
import 'package:hoshan/ui/screens/setting/cubit/report_pi_coin_cubit.dart';
import 'package:hoshan/ui/screens/setting/edit_profile_page.dart';
import 'package:hoshan/ui/screens/setting/income_page.dart';
import 'package:hoshan/ui/screens/setting/my_account_page.dart';
import 'package:hoshan/ui/screens/setting/setting_page.dart';
import 'package:hoshan/ui/screens/setting/utilization_report_page.dart';
import 'package:hoshan/ui/screens/splash/cubit/user_info_cubit.dart';
import 'package:hoshan/ui/screens/splash/splash_page.dart';
import 'package:hoshan/ui/screens/ticket/bloc/send_ticket_bloc.dart';
import 'package:hoshan/ui/screens/ticket/ticket_page.dart';
import 'package:hoshan/ui/screens/tools/single_tool_page.dart';
import 'package:hoshan/ui/screens/tools/tools_page.dart';

class Routes {
  static const String main = '/';
  static const String onBoarding = '/on-boarding';
  static const String auth = '/auth';

  static const String giftCredit = '/gift-credit';

  static const String home = '/home';
  static const String setting = '$home/setting';
  static const String cmp = '$home/cmp';
  static const String generatPhoto = '$home/generator-photo';
  static const String generatAudio = '$home/generator-audio';
  static const String generatVideo = '$home/generator-video';
  static const String editProfile = '$home/edit-profile';
  static const String utilizationReport = '$home/utilization-report';
  static const String myAccount = '$home/my-account';
  static const String otherProducts = '$home/other-products';
  static const String chat = '$home/chat';
  static const String ticket = '$home/ticket';
  static const String income = '$home/income';
  static const String purchase = '$home/purchase';
  static const String createAssistant = '$home/create-assistant';
  static const String returnToApp = '/return-to-app';
  static const String assistant = '$home/assistant';
  static const String chatFromAssistant = '$assistant/chat';
  static const String faq = '$home/faq';
  static const String tools = '$home/tools';
  static const String singleTool = '$home/single-tool';
  static const String chatFromSingleTool = '$singleTool/chat';

  static const String photoToPhoto = '$generatPhoto/ptp';
  static const String textToAudio = '$generatAudio/tta';

  static bool showOnBoarding = true;
  static Categories? categories;
  static ChatArgs? chatArgs;
  static int? lastPhotoId;

  static GoRoute _chatRoute(String path) => GoRoute(
        path: path,
        builder: (context, state) {
          try {
            if (state.extra != null) {
              chatArgs = state.extra as ChatArgs;
            }
          } catch (e) {
            if (kDebugMode) {
              print('Error get Args: $e');
            }
          }
          if (chatArgs != null) {
            final args = chatArgs!;
            return MultiBlocProvider(
              providers: [
                BlocProvider<MessagesBloc>(
                  create: (context) {
                    MessagesBloc messagesBloc = MessagesBloc();
                    if (args.chatId != null) {
                      messagesBloc.add(GetallMessages(chatId: args.chatId!));
                    }
                    if (args.messages != null) {
                      List<Content> cs = [];
                      for (var content in args.messages!.content!) {
                        if (content.type != 'text') {
                          cs.add(content);
                        }
                      }
                      messagesBloc.add(AddMessage(
                          message: Messages(
                        query: args.messages!.query,
                        file: args.messages!.file,
                        content: [
                          ...cs,
                          Content(text: args.messages!.query, type: 'text'),
                        ],
                        role: 'human',
                        createdAt: DateTimeUtils.getNow().toIso8601String(),
                        id: 'hero',
                      )));
                    }

                    return messagesBloc;
                  },
                ),
                BlocProvider<ReceiveMessageCubit>(
                  create: (context) {
                    ReceiveMessageCubit receiveMessageCubit =
                        ReceiveMessageCubit();
                    if (args.messages != null) {
                      receiveMessageCubit.execute(
                        request: SendMessageModel(
                          botId: args.bot.id,
                          file: args.messages!.file,
                          messageId: 'hero',
                          query: args.messages!.query!,
                          tool: args.bot.tool,
                        ),
                      );
                    }
                    return receiveMessageCubit;
                  },
                ),
                BlocProvider<RelatedQuestionsBloc>(
                  create: (context) => RelatedQuestionsBloc(),
                ),
              ],
              child: ChatPage(
                chatArgs: args,
              ),
            );
          } else {
            context.pop();
            return const SizedBox.shrink();
          }
        },
      );

  static final GoRouter routeGenerator = GoRouter(
    initialLocation: main,
    navigatorKey: navigatorKey,
    redirect: (context, state) async {
      final uri = state.uri;

      final token = uri.queryParameters['token'];
      final hasToken = token != null && token.isNotEmpty;

      final isCustomScheme = uri.scheme == 'houshan' && uri.host == 'auth';

      if (hasToken) {
        if (isCustomScheme || kIsWeb || uri.path == '/') {
          if (kDebugMode) {
            print('✅ Login Token Detected: ${token.substring(0, 10)}...');
          }
          await AuthTokenStorage.setToken(token);
          await OnBoardingStorage.setAsSeen();
          showOnBoarding = false;
          return main;
        }
      }

      if (AuthTokenStorage.getToken().isEmpty) {
        try {
          showOnBoarding = state.extra as bool;
        } catch (e) {
          showOnBoarding = !OnBoardingStorage.hasSeen();
          if (kDebugMode) {
            print('Error get Args: $e');
            print('Onboarding seen status: ${OnBoardingStorage.hasSeen()}');
          }
        }
        return auth;
      }

      if (state.uri.path == auth) {
        if (context.read<UserInfoCubit>().state is UserInfoFail) return null;
        if (AuthTokenStorage.getToken().isNotEmpty ||
            (UserInfoCubit.userInfoModel.login != null &&
                !(UserInfoCubit.userInfoModel.login!))) {
          return main;
        }
      }
      if (state.uri.path == home && kIsWeb) {
        if (UserInfoCubit.userInfoModel.login == null) {
          return main;
        } else {
          if (!(UserInfoCubit.userInfoModel.login!)) {
            return main;
          }
        }
      }

      return null;
    },
    routes: [
      GoRoute(
        path: main,
        builder: (context, state) {
          return const SplashPage();
        },
      ),
      GoRoute(
        path: giftCredit,
        builder: (context, state) {
          return const GiftCreditScreen();
        },
      ),
      GoRoute(
        path: auth,
        builder: (context, state) {
          try {
            showOnBoarding = state.extra as bool;
          } catch (e) {
            showOnBoarding = !OnBoardingStorage.hasSeen();
            if (kDebugMode) {
              print('Error get Args: $e');
            }
          }
          return MultiBlocProvider(
              providers: [
                BlocProvider<AuthScreensCubit>(
                  create: (context) => AuthScreensCubit(),
                )
              ],
              child: AuthPage(
                show: showOnBoarding,
              ));
        },
      ),
      GoRoute(
          path: home,
          builder: (context, state) {
            HomeArgs? args;

            try {
              args = state.extra as HomeArgs?;
            } catch (e) {
              if (kDebugMode) {
                print('erros in purchase show: $e');
              }
            }
            return MultiBlocProvider(
              providers: [
                BlocProvider<BannersCubit>(
                  create: (context) => BannersCubit()..getBanners(),
                ),
                BlocProvider<CoursesBloc>(
                  create: (context) => CoursesBloc(),
                ),
                BlocProvider<CommentsCubit>(
                  create: (context) => CommentsCubit()..loadComments(cId: 1),
                ),
                BlocProvider<BestAssistantsCubit>(
                  create: (context) => BestAssistantsCubit()..getAssistants(),
                ),
              ],
              child: HomePage(
                args: args,
              ),
            );
          },
          routes: [
            GoRoute(
              path: setting.substring(home.length + 1),
              builder: (context, state) {
                return const SettingPage();
              },
            ),
            GoRoute(
              path: cmp.substring(home.length + 1),
              builder: (context, state) {
                return const CmpPage();
              },
            ),
            GoRoute(
                path: generatPhoto.substring(home.length + 1),
                builder: (context, state) {
                  try {
                    final id = state.extra as int;
                    lastPhotoId = id;
                  } catch (e) {
                    lastPhotoId = null;
                    if (kDebugMode) {
                      print(e);
                    }
                    final id = state.uri.queryParameters['id'];
                    if (id != null) {
                      lastPhotoId = int.parse(id);
                    }
                  }
                  if (lastPhotoId != null) {
                    context.read<SingleMediaCubit>().getMediaById(lastPhotoId!);
                  }
                  return const GeneratePhotoPage();
                },
                routes: [
                  GoRoute(
                      path: 'ptp',
                      builder: (context, state) {
                        try {
                          if (state.extra != null) {
                            chatArgs = state.extra as ChatArgs;
                          }
                        } catch (e) {
                          if (kDebugMode) {
                            print('Error get Args: $e');
                          }
                        }
                        if (chatArgs == null) {
                          context.pop();
                          return const SizedBox();
                        }
                        return MultiBlocProvider(
                          providers: [
                            BlocProvider<MessagesBloc>(
                              create: (context) {
                                final messagesBloc = MessagesBloc();
                                if (chatArgs!.chatId != null) {
                                  messagesBloc.add(GetallMessages(
                                      chatId: chatArgs!.chatId!));
                                }
                                return messagesBloc;
                              },
                            ),
                            BlocProvider<MediaGResponseCubit>(
                              create: (context) {
                                return MediaGResponseCubit();
                              },
                            ),
                          ],
                          child: PhotoChatPage(
                            chatArgs: chatArgs!,
                          ),
                        );
                      })
                ]),
            GoRoute(
              path: generatVideo.substring(home.length + 1),
              builder: (context, state) {
                int? id;
                try {
                  final i = state.extra as int;
                  id = i;
                } catch (e) {
                  lastPhotoId = null;
                  if (kDebugMode) {
                    print(e);
                  }
                  final i = state.uri.queryParameters['id'];
                  if (i != null) {
                    id = int.parse(i);
                  }
                }
                if (id == null) {
                  context.pop();
                  return SizedBox();
                }
                return GenerateVideoPage(id: id);
              },
            ),
            GoRoute(
                path: generatAudio.substring(home.length + 1),
                builder: (context, state) {
                  int? id;
                  try {
                    final i = state.extra as int;
                    id = i;
                  } catch (e) {
                    lastPhotoId = null;
                    if (kDebugMode) {
                      print(e);
                    }
                    final i = state.uri.queryParameters['id'];
                    if (i != null) {
                      id = int.parse(i);
                    }
                  }
                  if (id == null) {
                    context.pop();
                    return SizedBox();
                  }
                  return GenerateAudioPage(
                    id: id,
                  );
                },
                routes: const []),
            GoRoute(
              path: editProfile.substring(home.length + 1),
              builder: (context, state) {
                return BlocProvider<CheckUsernameCubit>(
                  create: (context) => CheckUsernameCubit(),
                  child: const EditProfilePage(),
                );
              },
            ),
            GoRoute(
              path: utilizationReport.substring(home.length + 1),
              builder: (context, state) {
                return MultiBlocProvider(
                  providers: [
                    BlocProvider<ReportPiCoinCubit>(
                      create: (context) => ReportPiCoinCubit()..getReport(),
                    ),
                    BlocProvider<ReportOfUseBloc>(
                      create: (context) =>
                          ReportOfUseBloc()..add(const GetReport()),
                    )
                  ],
                  child: const UtilizationReportPage(),
                );
              },
            ),
            GoRoute(
              path: myAccount.substring(home.length + 1),
              builder: (context, state) {
                return const MyAccountPage();
              },
            ),
            _chatRoute(chat.substring(home.length + 1)),
            GoRoute(
              path: ticket.substring(home.length + 1),
              builder: (context, state) {
                return BlocProvider(
                  create: (context) => SendTicketBloc()..add(GetTickets()),
                  child: const TicketPage(),
                );
              },
            ),
            GoRoute(
              path: income.substring(home.length + 1),
              builder: (context, state) {
                return const IncomePage();
              },
            ),
            GoRoute(
              path: purchase.substring(home.length + 1),
              builder: (context, state) {
                PurchaseArgs? args;
                if (state.uri.hasQuery) {
                  try {
                    final success =
                        state.uri.queryParameters['status'] == 'success';
                    final message = state.uri.queryParameters['msg'] ?? '';
                    final credit = int.tryParse(
                            state.uri.queryParameters['credit'].toString()) ??
                        0;
                    args = PurchaseArgs(
                        message: message, success: success, credit: credit);
                  } catch (e) {
                    if (kDebugMode) {
                      print('erros in purchase show: $e');
                    }
                  }
                }

                return BlocProvider<PlansBloc>(
                  create: (context) => PlansBloc()..add(GetAllPlans()),
                  child: PurchasePage(
                    args: args,
                  ),
                );
              },
            ),
            GoRoute(
              path: createAssistant.substring(home.length + 1),
              builder: (context, state) {
                return MultiBlocProvider(
                  providers: [
                    BlocProvider<CheckUsernameCubit>(
                        create: (context) => CheckUsernameCubit()),
                    BlocProvider<CreateAssistantBloc>(
                      create: (context) => CreateAssistantBloc(),
                    ),
                    BlocProvider<DeleteAssistantCubit>(
                      create: (context) => DeleteAssistantCubit(),
                    ),
                  ],
                  child: CreateAssistantPage(
                    info: state.extra as AssistantPersonalInfo?,
                  ),
                );
              },
            ),
            GoRoute(
                path: assistant.substring(home.length + 1),
                builder: (context, state) {
                  return MultiBlocProvider(
                    providers: [
                      BlocProvider<SameAssistantsBloc>(
                          create: (context) => SameAssistantsBloc()),
                      BlocProvider<AssistantCommentsCubit>(
                          create: (context) => AssistantCommentsCubit()),
                      BlocProvider<AssistantInfoBloc>(
                        create: (context) => AssistantInfoBloc()
                          ..add(Getinfo(id: state.extra as int)),
                      )
                    ],
                    child: const AssistantPage(),
                  );
                },
                routes: [_chatRoute(chat.substring(home.length + 1))]),
            GoRoute(
              path: faq.substring(home.length + 1),
              builder: (context, state) {
                return const FaqPage();
              },
            ),
            GoRoute(
              path: tools.substring(home.length + 1),
              builder: (context, state) {
                return const ToolsPage();
              },
            ),
            GoRoute(
                path: singleTool.substring(home.length + 1),
                builder: (context, state) {
                  try {
                    if (state.extra != null) {
                      categories = state.extra as Categories;
                    }
                  } catch (e) {
                    if (kDebugMode) {
                      print('Error get Args: $e');
                    }
                  }
                  if (categories == null) {
                    context.pop();
                    return const SizedBox.shrink();
                  } else {
                    return SingleToolPage(
                      cat: categories!,
                    );
                  }
                },
                routes: [_chatRoute(chat.substring(home.length + 1))])
          ]),
    ],
  );
}
