import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../../app.dart';
import '../../../core/services/auth_service.dart';
import '../../../core/utils/snackbar_util.dart';
import '../../../core/design_system/app_components/auth_shell.dart';
import '../../../core/design_system/app_components/app_card.dart';
import '../../../core/design_system/app_spacing.dart';
import '../../../core/design_system/app_text.dart';
import '../../../l10n/l10n_x.dart';

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

  @override
  State<SignupScreen> createState() => _SignupScreenState();
}

class _SignupScreenState extends State<SignupScreen> {
  final _formKey = GlobalKey<FormState>();
  final _mobileController = TextEditingController();
  final _fullNameController = TextEditingController();
  final _passwordController = TextEditingController();
  final _confirmPasswordController = TextEditingController();
  final _emailController = TextEditingController();
  final _addressController = TextEditingController();
  final _emergencyContactController = TextEditingController();
  final _authService = Get.find<AuthService>();
  bool _isPasswordVisible = false;
  bool _isConfirmPasswordVisible = false;

  @override
  void dispose() {
    _mobileController.dispose();
    _fullNameController.dispose();
    _passwordController.dispose();
    _confirmPasswordController.dispose();
    _emailController.dispose();
    _addressController.dispose();
    _emergencyContactController.dispose();
    super.dispose();
  }

  Future<void> _handleSignup() async {
    if (_formKey.currentState!.validate()) {
      final success = await _authService.signup(
        _mobileController.text.trim(),
        _fullNameController.text.trim(),
        _passwordController.text,
        email: _emailController.text.trim().isEmpty ? null : _emailController.text.trim(),
        address: _addressController.text.trim().isEmpty ? null : _addressController.text.trim(),
        emergencyContact: _emergencyContactController.text.trim().isEmpty ? null : _emergencyContactController.text.trim(),
      );

      if (!mounted) return;
      final l = context.l10n;

      if (success) {
        SnackbarUtil.showSuccess(
          l.signupSuccessWelcome,
          title: l.snackTitleSuccess,
        );
        Get.offAll(() => const App());
      } else {
        SnackbarUtil.showError(
          l.signupFailedGenericUi,
          title: l.signupFailedTitle,
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final l = context.l10n;
    final scheme = Theme.of(context).colorScheme;
    return Scaffold(
      body: AuthShell(
        child: SingleChildScrollView(
          child: AppCard(
            padding: AppSpacing.all(AppSpacing.lg),
            child: Form(
              key: _formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(
                    Icons.account_balance_wallet_rounded,
                    size: 56.w,
                    color: scheme.primary,
                  ),
                  SizedBox(height: 16.h),
                  Text(l.authSignupScreenTitle, style: AppText.headline(context), textAlign: TextAlign.center),
                  SizedBox(height: 6.h),
                  Text(
                    l.authSignupTagline,
                    style: AppText.bodyMuted(context),
                    textAlign: TextAlign.center,
                  ),
                  SizedBox(height: 24.h),
                  TextFormField(
                    controller: _mobileController,
                    keyboardType: TextInputType.phone,
                    textInputAction: TextInputAction.next,
                    decoration: InputDecoration(
                      labelText: l.labelMobileNumberRequired,
                      prefixIcon: const Icon(Icons.phone_rounded),
                    ),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return l.validatorEnterMobile;
                      }
                      if (value.length != 10) {
                        return l.validatorMobileTenDigits;
                      }
                      if (!RegExp(r'^[0-9]+$').hasMatch(value)) {
                        return l.validatorMobileDigitsOnly;
                      }
                      return null;
                    },
                  ),
                  SizedBox(height: 20.h),
                  TextFormField(
                    controller: _fullNameController,
                    keyboardType: TextInputType.name,
                    textInputAction: TextInputAction.next,
                    decoration: InputDecoration(
                      labelText: l.labelFullNameRequired,
                      prefixIcon: const Icon(Icons.person_rounded),
                    ),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return l.validatorEnterFullName;
                      }
                      return null;
                    },
                  ),
                  SizedBox(height: 20.h),
                  TextFormField(
                    controller: _emailController,
                    keyboardType: TextInputType.emailAddress,
                    textInputAction: TextInputAction.next,
                    decoration: InputDecoration(
                      labelText: l.labelEmailOptional,
                      prefixIcon: const Icon(Icons.email_rounded),
                    ),
                    validator: (value) {
                      if (value != null && value.isNotEmpty) {
                        if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(value)) {
                          return l.validatorValidEmail;
                        }
                      }
                      return null;
                    },
                  ),
                  SizedBox(height: 20.h),
                  TextFormField(
                    controller: _addressController,
                    keyboardType: TextInputType.streetAddress,
                    maxLines: 2,
                    textInputAction: TextInputAction.newline,
                    decoration: InputDecoration(
                      labelText: l.labelAddressOptional,
                      prefixIcon: const Icon(Icons.home_rounded),
                    ),
                  ),
                  SizedBox(height: 20.h),
                  TextFormField(
                    controller: _emergencyContactController,
                    keyboardType: TextInputType.phone,
                    textInputAction: TextInputAction.next,
                    decoration: InputDecoration(
                      labelText: l.labelEmergencyContactOptional,
                      prefixIcon: const Icon(Icons.contact_phone_rounded),
                    ),
                    validator: (value) {
                      if (value != null && value.isNotEmpty) {
                        if (value.length != 10) {
                          return l.validatorEmergencyTenDigits;
                        }
                        if (!RegExp(r'^[0-9]+$').hasMatch(value)) {
                          return l.validatorEmergencyDigitsOnly;
                        }
                      }
                      return null;
                    },
                  ),
                  SizedBox(height: 20.h),
                  TextFormField(
                    controller: _passwordController,
                    obscureText: !_isPasswordVisible,
                    textInputAction: TextInputAction.next,
                    decoration: InputDecoration(
                      labelText: l.labelPasswordRequired,
                      prefixIcon: const Icon(Icons.lock_rounded),
                      suffixIcon: IconButton(
                        tooltip: _isPasswordVisible ? l.tooltipHidePassword : l.tooltipShowPassword,
                        icon: Icon(_isPasswordVisible ? Icons.visibility : Icons.visibility_off),
                        onPressed: () => setState(() => _isPasswordVisible = !_isPasswordVisible),
                      ),
                    ),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return l.validatorEnterPasswordAuth;
                      }
                      if (value.length < 6) {
                        return l.validatorPasswordMinSixAuth;
                      }
                      return null;
                    },
                  ),
                  SizedBox(height: 20.h),
                  TextFormField(
                    controller: _confirmPasswordController,
                    obscureText: !_isConfirmPasswordVisible,
                    textInputAction: TextInputAction.done,
                    decoration: InputDecoration(
                      labelText: l.labelConfirmPasswordRequired,
                      prefixIcon: const Icon(Icons.lock_outline_rounded),
                      suffixIcon: IconButton(
                        tooltip: _isConfirmPasswordVisible ? l.tooltipHidePassword : l.tooltipShowPassword,
                        icon: Icon(_isConfirmPasswordVisible ? Icons.visibility : Icons.visibility_off),
                        onPressed: () => setState(() => _isConfirmPasswordVisible = !_isConfirmPasswordVisible),
                      ),
                    ),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return l.validatorConfirmPassword;
                      }
                      if (value != _passwordController.text) {
                        return l.validatorPasswordsMismatch;
                      }
                      return null;
                    },
                  ),
                  SizedBox(height: 28.h),
                  Obx(() => SizedBox(
                        width: double.infinity,
                        height: 52.h,
                        child: FilledButton(
                          onPressed: _authService.isLoading.value ? null : _handleSignup,
                          child: _authService.isLoading.value
                              ? SizedBox(
                                  height: 24.h,
                                  width: 24.w,
                                  child: CircularProgressIndicator(
                                    strokeWidth: 2,
                                    valueColor: AlwaysStoppedAnimation<Color>(scheme.onPrimary),
                                  ),
                                )
                              : Text(l.createAccountButton),
                        ),
                      )),
                  SizedBox(height: 20.h),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        l.alreadyHaveAccount,
                        style: AppText.bodyMuted(context),
                      ),
                      TextButton(
                        onPressed: () => Get.back(),
                        child: Text(
                          l.loginLink,
                          style: AppText.label(context).copyWith(color: scheme.primary),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
