// ignore_for_file: deprecated_member_use_from_same_package, deprecated_member_use

import 'dart:async';

import 'package:app_links/app_links.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:hoshan/core/gen/assets.gen.dart';
import 'package:hoshan/core/routes/route_generator.dart';
import 'package:hoshan/data/model/auth/auth_screens_enum.dart';
import 'package:hoshan/data/storage/shared_preferences_helper.dart';
import 'package:hoshan/ui/screens/auth/code/bloc/check_code_bloc.dart';
import 'package:hoshan/ui/screens/auth/code/gift_code_screen.dart';
import 'package:hoshan/ui/screens/auth/cubit/auth_screens_cubit.dart';

import 'package:hoshan/ui/screens/auth/on_boarding/on_boarding_page.dart';
import 'package:hoshan/ui/screens/auth/register/bloc/register_bloc.dart';
import 'package:hoshan/ui/screens/auth/register/register_screen.dart';
import 'package:hoshan/ui/screens/auth/verification/bloc/verification_bloc.dart';
import 'package:hoshan/ui/screens/auth/verification/verification_screen.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/button/circle_icon_btn.dart';
import 'package:url_launcher/url_launcher.dart';

class AuthPage extends StatefulWidget {
  final bool show;
  const AuthPage({super.key, this.show = true});

  @override
  State<AuthPage> createState() => _AuthPageState();
}

class _AuthPageState extends State<AuthPage> {
  late bool onBoarding = widget.show;
  StreamSubscription? _linkSubscription;

  @override
  void initState() {
    super.initState();
    _initDeepLinkListener();
  }

  void _initDeepLinkListener() {
    if (!kIsWeb) {
      final appLinks = AppLinks();
      _linkSubscription = appLinks.uriLinkStream.listen((uri) async {
        print('🔔 AuthPage Listener Received URI: $uri'); // Debug Log
        
        final isCustomScheme = uri.scheme == 'houshan' && uri.host == 'auth';
        final isWebLink = (uri.scheme == 'https' || uri.scheme == 'http') && 
                          uri.host == 'basaweb.houshan.ai';

        if (isCustomScheme || isWebLink) {
          final token = uri.queryParameters['token'];
          if (token != null && token.isNotEmpty) {
            if (kDebugMode) {
              print('Deep link received: $uri');
            }
            await AuthTokenStorage.setToken(token);
            await OnBoardingStorage.setAsSeen();
            if (mounted) {
              context.read<UserInfoCubit>().getUserInfo();
              context.go(Routes.main);
            }
          }
        }
      });
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        return context.read<AuthScreensCubit>().state ==
                    AuthScreens.verification ||
                context.read<AuthScreensCubit>().state == AuthScreens.code
            ? false
            : true;
      },
      child: Scaffold(
        resizeToAvoidBottomInset: true,
        bottomNavigationBar:
            Responsive(context).isMobile() && onBoarding ? null : footer(),
        body: Stack(
          children: [
            Responsive(context).builder(
              mobile: onBoarding
                  ? OnBoardingPage(
                      onFinish: () {
                        // OnBoardingStorage.setBoradingStatus(false);
                        setState(() {
                          onBoarding = false;
                        });
                      },
                    )
                  : authScreen(),
              desktop: Row(
                children: [
                  SizedBox(
                    width: MediaQuery.sizeOf(context).width * 0.1,
                  ),
                  const Expanded(child: OnBoardingPage()),
                  SizedBox(
                    width: MediaQuery.sizeOf(context).width * 0.1,
                  ),
                  Expanded(
                      child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: authScreen(),
                  )),
                  SizedBox(
                    width: MediaQuery.sizeOf(context).width * 0.1,
                  ),
                ],
              ),
            ),
            Positioned(
                top: 46,
                right: 16,
                child: BlocBuilder<ThemeModeCubit, ThemeMode>(
                  builder: (context, state) {
                    return CircleIconBtn(
                      onTap: context.read<ThemeModeCubit>().switchTheme,
                      icon: (state == ThemeMode.dark
                          ? Assets.icon.outline.moon
                          : Assets.icon.outline.sun),
                      iconColor: Theme.of(context).colorScheme.onSurface,
                      color: Theme.of(context).colorScheme.surface,
                      size: 40,
                      iconPadding: const EdgeInsets.all(10),
                    );
                  },
                ))
          ],
        ),
      ),
    );
  }

  Widget authScreen() {
    return SingleChildScrollView(
      child: ConstrainedBox(
        constraints:
            BoxConstraints(minHeight: MediaQuery.sizeOf(context).height * 0.85),
        child: Column(
          children: [
            const SizedBox(
              height: 120,
            ),
            header(),
            BlocBuilder<AuthScreensCubit, AuthScreens>(
              builder: (context, state) {
                Widget mainScreen;
                if (state == AuthScreens.mobile) {
                  mainScreen = const RegisterScreen();
                } else if (state == AuthScreens.code) {
                  mainScreen = const GiftCodeScreen();
                } else {
                  mainScreen = const VerificationScreen();
                }
                return Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const SizedBox(
                      height: 24,
                    ),
                    MultiBlocProvider(
                      providers: [
                        BlocProvider<RegisterBloc>(
                          create: (context) => RegisterBloc(),
                        ),
                        BlocProvider<VerificationBloc>(
                          create: (context) => VerificationBloc(),
                        ),
                        BlocProvider<CheckCodeBloc>(
                          create: (context) => CheckCodeBloc(),
                        ),
                      ],
                      child: mainScreen,
                    ),

                    // if (state != AuthScreens.code &&
                    //     state != AuthScreens.verification)
                    //   Column(
                    //     children: [
                    //       Padding(
                    //         padding: const EdgeInsets.symmetric(vertical: 16.0),
                    //         child: Text(
                    //           'یا',
                    //           style: AppTextStyles.body3,
                    //         ),
                    //       ),
                    //       SizedBox(
                    //         width: MediaQuery.sizeOf(context).width,
                    //         height: 48,
                    //         child: Padding(
                    //           padding:
                    //               const EdgeInsets.symmetric(horizontal: 16.0),
                    //           child: ElevatedButton(
                    //               style: ElevatedButton.styleFrom(
                    //                 backgroundColor: Colors.white,
                    //                 shape: RoundedRectangleBorder(
                    //                     side: BorderSide(
                    //                         color: AppColors
                    //                             .primaryColor.defaultShade,
                    //                         width: 1.5),
                    //                     borderRadius:
                    //                         BorderRadius.circular(100)),
                    //               ),
                    //               onPressed: () async {
                    //                 try {
                    //                   await AuthService().signInWithGoogle();
                    //                 } on PlatformException catch (e) {
                    //                   if (e.code == 'sign_in_failed') {
                    //                     throw Exception(
                    //                         'Google Sign In failed. Please check your Google account and try again.');
                    //                   } else {
                    //                     throw Exception(
                    //                         'An error occurred while signing in with Google: ${e.message}');
                    //                   }
                    //                 } catch (e) {
                    //                   throw Exception(
                    //                       'An error occurred while signing in with Google: ${e.toString()}');
                    //                 }
                    //               },
                    //               child: Row(
                    //                 mainAxisSize: MainAxisSize.min,
                    //                 children: [
                    //                   Text(
                    //                     'ورود با حساب گوگل',
                    //                     style: AppTextStyles.body4.copyWith(
                    //                         color: AppColors
                    //                             .primaryColor.defaultShade),
                    //                   ),
                    //                   const SizedBox(
                    //                     width: 8,
                    //                   ),
                    //                   Assets.icon.signin.igoogle.svg(),
                    //                 ],
                    //               )),
                    //         ),
                    //       ),
                    //     ],
                    //   )
                  ],
                );
              },
            )
          ],
        ),
      ),
    );
  }

  Center header() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 32),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Assets.icon.launcherIcons.houshanIconPrimary
                .image(width: 150, height: 150, fit: BoxFit.cover),
            Text("هـوشان",
                style: AppTextStyles.headline1.copyWith(
                  color: Theme.of(context).colorScheme.primary,
                )),
            SizedBox(
              height: 15,
            ),
            Text(
              '"ویژه کارکنان فولاد مبارکه و خانواده محترم آن‌ها"',
              style: AppTextStyles.headline1.copyWith(
                  fontWeight: FontWeight.bold,
                  fontSize: 16,
                  color: context.read<ThemeModeCubit>().isDark()
                      ? Colors.white70
                      : Color.fromARGB(255, 61, 61, 61)),
            )
          ],
        ),
      ),
    );
  }

  Padding footer() {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 12.0),
      child: RichText(
          textAlign: TextAlign.center,
          textDirection: TextDirection.rtl,
          text: TextSpan(
              text: 'با ثبت نام و ورود به اپلیکیشن هوشان',
              style: AppTextStyles.body4.copyWith(
                  color: AppColors.gray[
                      context.read<ThemeModeCubit>().isDark() ? 600 : 900]),
              children: [
                const TextSpan(text: '، \n'),
                TextSpan(
                    text: 'شرایط و قوانین حریم خصوصی',
                    style: AppTextStyles.body4.copyWith(
                      color: Theme.of(context).colorScheme.primary,
                      fontWeight: FontWeight.bold,
                      decoration: TextDecoration.underline,
                    ),
                    recognizer: TapGestureRecognizer()
                      ..onTap = () async {
                        await launchUrl(
                                Uri.parse(
                                    'https://houshan.ai/%D9%82%D9%88%D8%A7%D9%86%DB%8C%D9%86-%D9%88-%D9%85%D9%82%D8%B1%D8%A7%D8%B1%D8%AA-%D8%AD%D9%81%D8%B8-%D8%AD%D8%B1%DB%8C%D9%85-%D8%AE%D8%B5%D9%88%D8%B5%DB%8C-%DA%A9%D8%A7%D8%B1%D8%A8%D8%B1%D8%A7%D9%86/'),
                                mode: LaunchMode.externalApplication)
                            .onError(
                          (error, stackTrace) {
                            if (kDebugMode) {
                              print('error open Link is: $error');
                            }
                            return false;
                          },
                        );
                      }),
                const TextSpan(text: ' را می‌‌پذیرم.'),
              ])),
    );
  }
}
