import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:kasy_kit/components/components.dart';
import 'package:kasy_kit/core/data/models/user.dart';
import 'package:kasy_kit/core/haptics/kasy_haptics.dart';
import 'package:kasy_kit/core/states/user_state_notifier.dart';
import 'package:kasy_kit/core/theme/theme.dart';
import 'package:kasy_kit/core/widgets/kasy_pressable_depth.dart';
import 'package:kasy_kit/core/widgets/page_background.dart';
import 'package:kasy_kit/features/authentication/providers/models/email.dart';
import 'package:kasy_kit/features/authentication/providers/models/password.dart';
import 'package:kasy_kit/features/authentication/providers/models/signin_state.dart';
import 'package:kasy_kit/features/authentication/providers/models/signup_state.dart';
import 'package:kasy_kit/features/authentication/providers/signin_state_provider.dart';
import 'package:kasy_kit/features/authentication/providers/signup_state_provider.dart';
import 'package:kasy_kit/features/authentication/ui/widgets/auth_brand.dart';
import 'package:kasy_kit/features/authentication/ui/widgets/auth_page_back_button.dart';
import 'package:kasy_kit/features/authentication/ui/widgets/social_separator.dart';
import 'package:kasy_kit/i18n/translations.g.dart';

final _formKey = GlobalKey<FormState>();
const double _authFieldSpacing = KasySpacing.md;
const double _authFieldToActionSpacing = KasySpacing.lg;

class SignupPage extends ConsumerWidget {
  final bool canDismiss;

  const SignupPage({super.key, this.canDismiss = true});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final user = ref.watch(userStateNotifierProvider).user;
    redirectIfAuthenticated(context, user);
    if (user is AuthenticatedUserData) {
      return const Scaffold(
        resizeToAvoidBottomInset: false,
        body: SizedBox.shrink(),
      );
    }
    final signupState = ref.watch(signupStateProvider);
    final isSignupSending = signupState is SignupStateSending;
    final isSocialSending =
        ref.watch(signinStateProvider) is SigninStateSending;
    final isSending = isSignupSending || isSocialSending;
    final showBack = shouldShowAuthBackButton(context);
    return PopScope(
      canPop: showBack || canDismiss,
      child: Scaffold(
          resizeToAvoidBottomInset: false,
          body: Stack(
            children: [
              Background(
                child: Form(
                  autovalidateMode: AutovalidateMode.disabled,
                  key: _formKey,
                  child: AuthFormScrollView(
                    children: [
                      const AuthBrand(),
                      const SizedBox(height: KasySpacing.xl),
                      Text(
                        t.auth.signup.title,
                        textAlign: TextAlign.center,
                        style: context.textTheme.headlineMedium?.copyWith(
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      const SizedBox(height: KasySpacing.xs),
                      Text(
                        t.auth.signup.subtitle,
                        textAlign: TextAlign.center,
                        style: context.textTheme.bodyMedium?.copyWith(
                          color: context.colors.onSurface.withValues(
                            alpha: 0.62,
                          ),
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      const SizedBox(height: KasySpacing.xl),
                      KasyTextField(
                        key: const Key('email_input'),
                        onChanged: (value) => ref
                            .read(signupStateProvider.notifier)
                            .setEmail(value),
                        hint: t.auth.signin.email_hint,
                        label: t.auth.signin.email_label,
                        contentType: KasyTextFieldContentType.email,
                        textInputAction: TextInputAction.next,
                        validator: (value) {
                          try {
                            signupState.email.validate();
                          } on EmailException catch (_) {
                            return t.auth.signin.email_invalid;
                          }
                          return null;
                        },
                      ),
                      const SizedBox(height: _authFieldSpacing),
                      KasyTextField(
                        key: const Key('password_input'),
                        onChanged: (newValue) => ref
                            .read(signupStateProvider.notifier)
                            .setPassword(newValue),
                        hint: t.auth.signin.password_hint,
                        label: t.auth.signin.password_label,
                        textInputAction: TextInputAction.done,
                        contentType: KasyTextFieldContentType.password,
                        onSubmitted: isSignupSending
                            ? null
                            : (_) {
                                if (!_formKey.currentState!.validate()) return;
                                FocusScope.of(context).unfocus();
                                ref.read(signupStateProvider.notifier).signup();
                              },
                        validator: (value) {
                          try {
                            signupState.password.validate();
                          } on PasswordException catch (_) {
                            if (value == null || value.trim().isEmpty) {
                              return t.auth.signin.password_required;
                            }
                            return t.auth.signin.password_too_short;
                          }
                          return null;
                        },
                      ),
                      const SizedBox(height: _authFieldToActionSpacing),
                      KasyButton(
                        key: const Key('send_button'),
                        label: t.auth.signup.submit,
                        isLoading: isSignupSending,
                        onPressed: isSignupSending
                            ? null
                            : () {
                                if (!_formKey.currentState!.validate()) {
                                  return;
                                }
                                FocusScope.of(context).unfocus();
                                ref.read(signupStateProvider.notifier).signup();
                              },
                        expand: true,
                      ),
                      const SizedBox(height: KasySpacing.xs),
                      const _SigninPrompt(),
                      const SizedBox(height: KasySpacing.lg),
                      const SocialSeparator(),
                      const SizedBox(height: KasySpacing.md),
                      const _SocialSignupRow(),
                    ],
                  ),
                ),
              ),
              const AuthPageBackButton(),
              if (isSending)
                Positioned.fill(
                  child: AbsorbPointer(
                    child: ClipRect(
                      child: BackdropFilter(
                        filter: ImageFilter.blur(sigmaX: 6, sigmaY: 6),
                        child: ColoredBox(
                          color: Colors.black.withValues(alpha: 0.15),
                          child: Center(
                            child: CircularProgressIndicator(
                              color: context.colors.primary,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
            ],
          ),
        ),
      );
  }
}

class _SigninPrompt extends StatelessWidget {
  const _SigninPrompt();

  @override
  Widget build(BuildContext context) {
    return Center(
      child: FittedBox(
        fit: BoxFit.scaleDown,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              t.auth.signup.have_account,
              style: context.textTheme.bodyMedium?.copyWith(
                color: context.colors.onSurface.withValues(alpha: 0.62),
                fontWeight: FontWeight.w500,
              ),
            ),
            const SizedBox(width: 4),
            KasyPressableDepth(
              semanticLabel: t.auth.signup.signin_link,
              onPressed: () => context.pushReplacement('/signin'),
              child: Text(
                t.auth.signup.signin_link,
                style: context.textTheme.bodyMedium?.copyWith(
                  color: context.colors.onSurface,
                  fontWeight: FontWeight.w800,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _SocialSignupRow extends ConsumerWidget {
  const _SocialSignupRow();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final state = ref.watch(signinStateProvider);
    final isSending = state is SigninStateSending;
    return Row(
      children: [
        Expanded(
          child: _SocialSignupTile(
            label: t.auth.signin.google,
            icon: Image.asset('assets/icons/google.png', width: 20, height: 20),
            onPressed: isSending
                ? null
                : () =>
                      ref.read(signinStateProvider.notifier).signinWithGoogle(),
          ),
        ),
        const SizedBox(width: KasySpacing.sm),
        Expanded(
          child: _SocialSignupTile(
            label: t.auth.signin.apple,
            icon: Image.asset('assets/icons/apple.png', width: 20, height: 20),
            onPressed: isSending
                ? null
                : () =>
                      ref.read(signinStateProvider.notifier).signinWithApple(),
          ),
        ),
        const SizedBox(width: KasySpacing.sm),
        Expanded(
          child: _SocialSignupTile(
            label: t.auth.signin.facebook,
            icon: Image.asset(
              'assets/icons/facebook.png',
              width: 20,
              height: 20,
            ),
            onPressed: isSending
                ? null
                : () => ref
                      .read(signinStateProvider.notifier)
                      .signinWithFacebook(),
          ),
        ),
      ],
    );
  }
}

class _SocialSignupTile extends StatelessWidget {
  const _SocialSignupTile({
    required this.label,
    required this.icon,
    required this.onPressed,
  });

  final String label;
  final Widget icon;
  final VoidCallback? onPressed;

  @override
  Widget build(BuildContext context) {
    final bool enabled = onPressed != null;
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: enabled
            ? () {
                KasyHaptics.medium(context);
                onPressed?.call();
              }
            : null,
        borderRadius: BorderRadius.circular(KasyRadius.md),
        child: Ink(
          height: 44,
          decoration: BoxDecoration(
            color: context.colors.surface,
            borderRadius: BorderRadius.circular(KasyRadius.sm),
            border: Border.all(
              color: context.colors.outline.withValues(alpha: 0.38),
            ),
          ),
          child: Center(
            child: Semantics(button: true, label: label, child: icon),
          ),
        ),
      ),
    );
  }
}
