import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'dart:math';
import 'dart:convert';
import '../blocs/auth/auth_bloc.dart';
import '../blocs/auth/auth_event.dart';
import '../blocs/auth/auth_state.dart';
import '../theme/app_theme.dart';
import '../theme/modern_glass_button.dart';

class SignupForm extends StatefulWidget {
  const SignupForm({super.key});

  @override
  State<SignupForm> createState() => _SignupFormState();
}

class _SignupFormState extends State<SignupForm> {
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  final _displayNameController = TextEditingController();

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    _displayNameController.dispose();
    super.dispose();
  }

  String _generateRandomBase64(int bytes) {
    final random = Random();
    final values = List<int>.generate(bytes, (i) => random.nextInt(256));
    return base64.encode(values);
  }

  Future<void> _handleRegistration(
    BuildContext context,
    RegistrationChallengeReceived state,
  ) async {
    try {
      // Simulate WebAuthn registration by generating fake credential data
      // In a real implementation, this would call native WebAuthn APIs
      final credentialId = _generateRandomBase64(64);
      final publicKey = _generateRandomBase64(91); // EC2 public key size

      if (context.mounted) {
        context.read<AuthBloc>().add(
          RegistrationResponseSubmitted(
            userId: state.userId,
            challenge: state.challenge,
            credentialId: credentialId,
            publicKey: publicKey,
            clientDataJSON:
                '{"type":"webauthn.create","challenge":"${state.challenge}","origin":"https://b0esche.cloud"}',
            attestationObject: _generateRandomBase64(128),
          ),
        );
      }
    } catch (e) {
      if (context.mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('Registration failed: $e')));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<AuthBloc, AuthState>(
      listener: (context, state) {
        if (state is AuthFailure) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(SnackBar(content: Text(state.error)));
        } else if (state is RegistrationChallengeReceived) {
          _handleRegistration(context, state);
        } else if (state is AuthAuthenticated) {
          context.go('/');
        }
      },
      child: Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const Text(
                  'create account',
                  style: TextStyle(fontSize: 24, color: AppTheme.primaryText),
                ),
                const SizedBox(height: 24),
                Container(
                  decoration: BoxDecoration(
                    color: AppTheme.primaryBackground.withValues(alpha: 0.5),
                    borderRadius: BorderRadius.circular(16),
                    border: Border.all(
                      color: AppTheme.accentColor.withValues(alpha: 0.3),
                    ),
                  ),
                  child: Column(
                    children: [
                      TextField(
                        controller: _usernameController,
                        textInputAction: TextInputAction.next,
                        keyboardType: TextInputType.text,
                        cursorColor: AppTheme.accentColor,
                        decoration: InputDecoration(
                          hintText: 'username',
                          hintStyle: TextStyle(color: AppTheme.secondaryText),
                          contentPadding: const EdgeInsets.all(12),
                          border: InputBorder.none,
                          prefixIcon: Icon(
                            Icons.person_outline,
                            color: AppTheme.primaryText,
                            size: 20,
                          ),
                        ),
                        style: const TextStyle(color: AppTheme.primaryText),
                      ),
                      Divider(
                        color: AppTheme.accentColor.withValues(alpha: 0.2),
                        height: 1,
                        thickness: 1,
                      ),
                      TextField(
                        controller: _passwordController,
                        textInputAction: TextInputAction.next,
                        keyboardType: TextInputType.visiblePassword,
                        obscureText: true,
                        cursorColor: AppTheme.accentColor,
                        decoration: InputDecoration(
                          hintText: 'password',
                          hintStyle: TextStyle(color: AppTheme.secondaryText),
                          contentPadding: const EdgeInsets.all(12),
                          border: InputBorder.none,
                          prefixIcon: Icon(
                            Icons.lock_outline,
                            color: AppTheme.primaryText,
                            size: 20,
                          ),
                        ),
                        style: const TextStyle(color: AppTheme.primaryText),
                      ),
                      Divider(
                        color: AppTheme.accentColor.withValues(alpha: 0.2),
                        height: 1,
                        thickness: 1,
                      ),
                      TextField(
                        controller: _displayNameController,
                        textInputAction: TextInputAction.done,
                        keyboardType: TextInputType.text,
                        cursorColor: AppTheme.accentColor,
                        decoration: InputDecoration(
                          hintText: 'display name (optional)',
                          hintStyle: TextStyle(color: AppTheme.secondaryText),
                          contentPadding: const EdgeInsets.all(12),
                          border: InputBorder.none,
                          prefixIcon: Icon(
                            Icons.badge_outlined,
                            color: AppTheme.primaryText,
                            size: 20,
                          ),
                        ),
                        style: const TextStyle(color: AppTheme.primaryText),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 16),
                SizedBox(
                  width: 150,
                  child: BlocBuilder<AuthBloc, AuthState>(
                    builder: (context, state) {
                      return ModernGlassButton(
                        isLoading: state is AuthLoading,
                        onPressed: () {
                          if (_usernameController.text.isEmpty ||
                              _passwordController.text.isEmpty) {
                            ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(
                                content: Text(
                                  'Username and password are required',
                                ),
                              ),
                            );
                            return;
                          }
                          context.read<AuthBloc>().add(
                            SignupStarted(
                              username: _usernameController.text,
                              email: _usernameController
                                  .text, // Use username as email for now
                              displayName: _displayNameController.text,
                              password: _passwordController.text,
                            ),
                          );
                        },
                        child: const Text('create'),
                      );
                    },
                  ),
                ),
                const SizedBox(height: 16),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      'already have an account?',
                      style: TextStyle(color: AppTheme.secondaryText),
                    ),
                    const SizedBox(width: 8),
                    GestureDetector(
                      onTap: () => context.go('/login'),
                      child: Text(
                        'sign in',
                        style: TextStyle(
                          color: AppTheme.accentColor,
                          decoration: TextDecoration.underline,
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
