import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:travel_mate/blocs/auth/auth_bloc.dart';
import 'package:travel_mate/blocs/auth/auth_event.dart';

class SignUpPlatformContent extends StatefulWidget {
  final String platform; // 'google' ou 'apple'
  final String? email;
  final String? phoneNumber;
  final String? name;
  final String? firstName;

  const SignUpPlatformContent({
    super.key,
    required this.platform,
    this.email,
    this.phoneNumber,
    this.name,
    this.firstName,
  });

  @override
  State<SignUpPlatformContent> createState() => _SignUpPlatformContentState();
}

class _SignUpPlatformContentState extends State<SignUpPlatformContent> {
  final _formKey = GlobalKey<FormState>();
  late TextEditingController _nameController;
  late TextEditingController _firstNameController;
  late TextEditingController _emailController;
  late TextEditingController _phoneController;

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController(text: widget.name ?? '');
    _firstNameController = TextEditingController(text: widget.firstName ?? '');
    _emailController = TextEditingController(text: widget.email ?? '');
    _phoneController = TextEditingController(text: widget.phoneNumber ?? '');
  }

  @override
  void dispose() {
    _nameController.dispose();
    _firstNameController.dispose();
    _emailController.dispose();
    _phoneController.dispose();
    super.dispose();
  }

  String? _validateField(String? value, String fieldName) {
    if (value == null || value.isEmpty) {
      return '$fieldName est requis';
    }
    return null;
  }

  void _submitForm() {
    if (!_formKey.currentState!.validate()) {
      return;
    }

    if (widget.platform == 'google') {
      context.read<AuthBloc>().add(
        AuthGoogleSignUpRequested(
          phoneNumber: _phoneController.text.trim(),
          name: _nameController.text.trim(),
          firstname: _firstNameController.text.trim(),
        ),
      );
    } else if (widget.platform == 'apple') {
      context.read<AuthBloc>().add(
        AuthAppleSignUpRequested(
          phoneNumber: _phoneController.text.trim(),
          name: _nameController.text.trim(),
          firstname: _firstNameController.text.trim(),
        ),
      );
    }
  }

  Widget _buildPlatformIndicator(ThemeData theme) {
    final isDark = theme.brightness == Brightness.dark;

    Color platformColor = widget.platform == 'google'
        ? Colors.red
        : Colors.black;
    String platformName = widget.platform == 'google' ? 'Google' : 'Apple';
    String platformIcon = widget.platform == 'google'
        ? 'assets/icons/google.png'
        : 'assets/icons/apple_white.png';

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: widget.platform == 'google'
            ? Colors.red.shade50
            : (isDark
                  ? Colors.grey[900]
                  : Colors.black.withValues(alpha: 0.05)),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: platformColor, width: 1),
      ),
      child: Row(
        children: [
          Image.asset(
            platformIcon,
            height: 24,
            width: 24,
          ),
          const SizedBox(width: 8),
          Text(
            'Connecté avec $platformName',
            style: TextStyle(
              color: platformColor,
              fontWeight: FontWeight.w500,
              fontSize: 16,
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final isDark = theme.brightness == Brightness.dark;

    return Scaffold(
      backgroundColor: theme.scaffoldBackgroundColor,
      appBar: AppBar(
        backgroundColor: theme.appBarTheme.backgroundColor,
        elevation: 0,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: theme.iconTheme.color),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(24.0),
          child: Form(
            key: _formKey,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                // Indicateur de plateforme
                _buildPlatformIndicator(theme),
                const SizedBox(height: 32),

                // Titre
                Text(
                  'Complétez votre profil',
                  style: theme.textTheme.headlineSmall?.copyWith(
                    fontWeight: FontWeight.bold,
                    color: isDark ? Colors.white : Colors.black,
                  ),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 8),

                Text(
                  'Vérifiez et complétez vos informations',
                  style: theme.textTheme.bodyLarge?.copyWith(
                    color: isDark ? Colors.grey[400] : Colors.grey[600],
                  ),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 32),

                // Champ Nom
                TextFormField(
                  controller: _nameController,
                  decoration: InputDecoration(
                    labelText: 'Nom',
                    border: const OutlineInputBorder(),
                    prefixIcon: const Icon(Icons.person_outline),
                    labelStyle: TextStyle(
                      color: isDark ? Colors.white70 : Colors.black87,
                    ),
                  ),
                  style: TextStyle(color: isDark ? Colors.white : Colors.black),
                  validator: (value) => _validateField(value, 'Nom'),
                ),
                const SizedBox(height: 16),

                // Champ Prénom
                TextFormField(
                  controller: _firstNameController,
                  decoration: InputDecoration(
                    labelText: 'Prénom',
                    border: const OutlineInputBorder(),
                    prefixIcon: const Icon(Icons.person_outline),
                    labelStyle: TextStyle(
                      color: isDark ? Colors.white70 : Colors.black87,
                    ),
                  ),
                  style: TextStyle(color: isDark ? Colors.white : Colors.black),
                  validator: (value) => _validateField(value, 'Prénom'),
                ),
                const SizedBox(height: 16),

                // Champ Email (non modifiable)
                TextFormField(
                  controller: _emailController,
                  decoration: InputDecoration(
                    labelText: 'Email',
                    border: const OutlineInputBorder(),
                    prefixIcon: const Icon(Icons.email_outlined),
                    suffixIcon: Icon(
                      Icons.lock_outline,
                      color: isDark ? Colors.grey[600] : Colors.grey[400],
                    ),
                    labelStyle: TextStyle(
                      color: isDark ? Colors.white70 : Colors.black87,
                    ),
                  ),
                  enabled: false,
                  style: TextStyle(
                    color: isDark ? Colors.grey[400] : Colors.grey[600],
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  'Email fourni par ${widget.platform == 'google' ? 'Google' : 'Apple'}',
                  style: TextStyle(
                    fontSize: 12,
                    color: isDark ? Colors.grey[500] : Colors.grey[600],
                  ),
                ),
                const SizedBox(height: 16),

                // Champ Téléphone
                TextFormField(
                  controller: _phoneController,
                  decoration: InputDecoration(
                    labelText: 'Numéro de téléphone',
                    border: const OutlineInputBorder(),
                    prefixIcon: const Icon(Icons.phone_outlined),
                    hintText: '+33 6 12 34 56 78',
                    labelStyle: TextStyle(
                      color: isDark ? Colors.white70 : Colors.black87,
                    ),
                    hintStyle: TextStyle(
                      color: isDark ? Colors.grey[600] : Colors.grey[400],
                    ),
                  ),
                  style: TextStyle(color: isDark ? Colors.white : Colors.black),
                  keyboardType: TextInputType.phone,
                  validator: (value) =>
                      _validateField(value, 'Numéro de téléphone'),
                ),
                const SizedBox(height: 32),

                // Bouton de confirmation
                ElevatedButton(
                  onPressed: _submitForm,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: isDark ? Colors.white : Colors.black,
                    foregroundColor: isDark ? Colors.black : Colors.white,
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: Text(
                    'Confirmer mon inscription',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color: isDark ? Colors.black : Colors.white,
                    ),
                  ),
                ),
                const SizedBox(height: 16),

                // Bouton secondaire
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  child: Text(
                    'Modifier la méthode de connexion',
                    style: TextStyle(
                      color: isDark ? Colors.grey[400] : Colors.grey,
                      fontSize: 14,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
