import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_sign_in/google_sign_in.dart';
import '../../services/firebase_service.dart';
import '../../services/emailjs_service.dart';
import '../../services/fonnte_service.dart';
import '../../services/google_signin_wrapper.dart';
import '../../widgets/auth/verification_step_widget.dart';
import '../../services/dialog_service.dart';
import '../../widgets/common/scale_button.dart';
import 'package:flutter_animate/flutter_animate.dart';
import '../home/home_screen.dart';
import '../onboarding/early_setup_screen.dart';

const Color primaryBrown = Color(0xFF4A3C3C);
const Color lightBrown = Color(0xFF6B5B5B);
const Color headerGradientStart = Color(0xFF5D4E4E);
const Color headerGradientEnd = Color(0xFF8B7B7B);

class LoginScreen extends ConsumerStatefulWidget {
  const LoginScreen({super.key});

  @override
  ConsumerState<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends ConsumerState<LoginScreen> {
  final _formKey = GlobalKey<FormState>();
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();

  bool _isLoading = false;
  bool _isGoogleLoading = false;
  bool _obscurePassword = true;
  AutovalidateMode _autoValidateMode = AutovalidateMode.disabled;

  // State for toggling between Login, Register, and Forgot Password
  bool _isRegistering = false;
  bool _isForgotPassword = false;
  int _forgotPasswordStep =
      0; // 0=Email, 1=ChooseVerification, 2=VerifyOTP, 3=NewPassword, 4=Success
  final List<TextEditingController> _codeControllers = List.generate(
    5,
    (index) => TextEditingController(),
  );
  int _registerStep =
      0; // 0=Profile, 1=ChooseVerification, 2=VerifyOTP, 3=Password, 4=Success
  String _verificationMethod = 'email'; // 'email' or 'wa'

  // New Controllers for expanded registration
  final _passwordRegisterController = TextEditingController();
  final _confirmPasswordController = TextEditingController();
  final _nameController = TextEditingController();
  final _phoneController = TextEditingController();

  // Timer for verification code
  Timer? _timer;
  Timer? _errorTimer; // For reverting error state
  int _remainingSeconds = 225; // 3 minutes 45 seconds
  bool _isCodeError = false; // Track if code is incorrect

  // Password Validation State
  bool _hasMinLength = false;
  bool _hasUppercase = false;
  bool _hasLowercase = false;
  bool _hasNumber = false;
  bool _passwordsMatch = false;

  // Email Validation State
  String? _emailError;

  // Login Validation State
  String? _loginEmailError;
  String? _loginPasswordError;

  // Biodata Validation State
  String? _nameError;
  String? _phoneError;

  // Track if user attempted to submit (to show validation errors)
  bool _showPasswordErrors = false;

  // Saved Google account for deferred Firebase sign-in
  GoogleSignInAccount? _pendingGoogleAccount;

  @override
  void dispose() {
    _emailController.dispose();
    _passwordController.dispose();
    // Dispose new controllers
    _passwordRegisterController.dispose();
    _confirmPasswordController.dispose();
    _nameController.dispose();
    _phoneController.dispose();

    for (var c in _codeControllers) c.dispose();
    _timer?.cancel();
    _errorTimer?.cancel();
    super.dispose();
  }

  void _startTimer() {
    _timer?.cancel();
    setState(() => _remainingSeconds = 225); // Reset to 3:45
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_remainingSeconds > 0) {
        if (mounted) setState(() => _remainingSeconds--);
      } else {
        timer.cancel();
      }
    });
  }

  String get _formattedTime {
    final minutes = (_remainingSeconds / 60).floor();
    final seconds = _remainingSeconds % 60;
    return '$minutes.${seconds.toString().padLeft(2, '0')}';
  }

  // Toggle between Login and Register
  void _toggleAuthMode() {
    setState(() {
      _isRegistering = !_isRegistering;
      _isForgotPassword = false; // Reset forgot password
      _registerStep = 0; // Reset register step
      _forgotPasswordStep = 0;
      _formKey.currentState?.reset();
      _timer?.cancel(); // Cancel timer if switching modes
      _errorTimer?.cancel();
      _isCodeError = false;
      // Reset validation states
      _emailError = null;
      _hasMinLength = false;
      _hasUppercase = false;
      _hasLowercase = false;
      _hasNumber = false;
      _passwordsMatch = false;
      _showPasswordErrors = false;
      _loginEmailError = null;
      _loginPasswordError = null;
      _nameError = null;
      _phoneError = null;
      // Clear all controllers except login email
      _passwordController.clear();
      _passwordRegisterController.clear();
      _confirmPasswordController.clear();
      _nameController.clear();
      _phoneController.clear();
      for (var c in _codeControllers) c.clear();
    });
  }

  void _toggleForgotPasswordMode() {
    setState(() {
      _isForgotPassword = !_isForgotPassword;
      _isRegistering = false;
      _forgotPasswordStep = 0;
      _registerStep = 0;
      _formKey.currentState?.reset();
      _timer?.cancel();
      _errorTimer?.cancel();
      _isCodeError = false;
      // Reset validation states
      _emailError = null;
      _hasMinLength = false;
      _hasUppercase = false;
      _hasLowercase = false;
      _hasNumber = false;
      _passwordsMatch = false;
      _showPasswordErrors = false;
      _loginEmailError = null;
      _loginPasswordError = null;
      _nameError = null;
      _phoneError = null;
      // Clear all controllers except login email
      _passwordController.clear();
      _passwordRegisterController.clear();
      _confirmPasswordController.clear();
      _nameController.clear();
      _phoneController.clear();
      for (var c in _codeControllers) c.clear();
    });
  }

  void _checkPasswordRequirements() {
    final password = _passwordRegisterController.text;
    final confirm = _confirmPasswordController.text;

    setState(() {
      _hasMinLength = password.length >= 8;
      _hasUppercase = password.contains(RegExp(r'[A-Z]'));
      _hasLowercase = password.contains(RegExp(r'[a-z]'));
      _hasNumber = password.contains(RegExp(r'[0-9]'));
      _passwordsMatch = password.isNotEmpty && password == confirm;
    });
  }

  String _getPasswordErrorText() {
    List<String> errors = [];
    if (!_hasMinLength) errors.add('minimal 8 karakter');
    if (!_hasUppercase) errors.add('huruf besar (A-Z)');
    if (!_hasLowercase) errors.add('huruf kecil (a-z)');
    if (!_hasNumber) errors.add('angka (0-9)');

    if (errors.isEmpty) return '';
    return 'Password harus mengandung ${errors.join(', ')}';
  }

  Future<void> _showCancelConfirmationDialog() async {
    String title = 'Batalkan Proses?';
    String content = _isForgotPassword
        ? 'Apakah anda yakin ingin membatalkan reset password?'
        : 'Apakah anda yakin ingin membatalkan registrasi?';

    final confirm = await DialogService().showConfirmDialog(
      title: title,
      message: content,
      confirmText: 'Ya, Batalkan',
      cancelText: 'Tidak',
      isDanger: true,
      context: context,
    );

    if (confirm && mounted) {
      setState(() {
        _isForgotPassword = false;
        _isRegistering = false;
        _forgotPasswordStep = 0;
        _registerStep = 0;
        _timer?.cancel();
        _errorTimer?.cancel();
        _isCodeError = false;
        _passwordController.clear();
        _passwordRegisterController.clear();
        _confirmPasswordController.clear();
        _nameController.clear();
        _phoneController.clear();
        for (var c in _codeControllers) c.clear();
      });
    }
  }

  Future<void> _signInWithEmail() async {
    // Validate email
    final email = _emailController.text.trim();
    if (email.isEmpty) {
      setState(() => _loginEmailError = 'Email tidak boleh kosong');
      return;
    }
    if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(email)) {
      setState(() => _loginEmailError = 'Format email tidak valid');
      return;
    }

    // Validate password
    final password = _passwordController.text;
    if (password.isEmpty) {
      setState(() => _loginPasswordError = 'Password tidak boleh kosong');
      return;
    }
    if (password.length < 6) {
      setState(() => _loginPasswordError = 'Password minimal 6 karakter');
      return;
    }

    setState(() => _isLoading = true);

    try {
      final firebaseService = FirebaseService();
      final userCredential = await firebaseService.signInWithEmail(
        _emailController.text.trim().toLowerCase(), // Hindari huruf kapital dari keyboard
        _passwordController.text.trim(), // Trim password untuk mencegah spasi tersembunyi
      );

      if (userCredential?.user != null && mounted) {
        final userData = await firebaseService.getUserData(
          userCredential!.user!.uid,
        );

        if (mounted) {
          if (userData == null || !userData.isSetupComplete) {
            Navigator.of(context).pushReplacement(
              MaterialPageRoute(builder: (context) => const EarlySetupScreen()),
            );
          } else {
            Navigator.of(context).pushReplacement(
              MaterialPageRoute(builder: (context) => const HomeScreen()),
            );
          }
        }
      }
    } catch (e) {
      if (mounted) {
        DialogService().showError(e.toString());
      }
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  Future<void> _handleRegister() async {
    final firebaseService = FirebaseService();

    // Step 0: Validate Profile (Name, Phone, Email)
    if (_registerStep == 0) {
      if (_nameController.text.trim().isEmpty) {
        setState(() => _nameError = 'Nama Lengkap harus diisi');
        return;
      }
      if (_phoneController.text.trim().isEmpty) {
        setState(() => _phoneError = 'Nomor Telepon harus diisi');
        return;
      }
      if (_phoneController.text.trim().length < 10) {
        setState(() => _phoneError = 'Nomor telepon tidak valid');
        return;
      }
      if (_emailController.text.isEmpty) {
        setState(() => _emailError = 'Email tidak boleh kosong');
        return;
      }
      if (!_emailController.text.contains('@')) {
        setState(() => _emailError = 'Email tidak valid');
        return;
      }

      // All valid -> go to Step 1 (Choose Verification Method)
      setState(() => _registerStep = 1);
    }
    // Step 1 is handled by _sendVerificationOTP()
    //
    // Step 2: Verify OTP Code
    else if (_registerStep == 2) {
      String code = _codeControllers.map((c) => c.text).join();

      if (code.length < 5) {
        setState(() => _isCodeError = true);
        return;
      }

      setState(() => _isLoading = true);

      // Artificial delay to show loading state (UX)
      await Future.delayed(const Duration(seconds: 2));

      try {
        bool isVerified;

        if (_verificationMethod == 'wa') {
          isVerified = FonnteService.verifyOTP(
            _phoneController.text.trim(),
            code,
          );
        } else {
          isVerified = EmailJSService.verifyOTP(
            _emailController.text.trim(),
            code,
          );
        }

        if (!isVerified) {
          setState(() {
            _isLoading = false;
            _isCodeError = true;
          });
          return;
        }

        // OTP verified -> Show success dialog then go to Step 3
        if (mounted) {
          setState(() => _isLoading = false);
          _timer?.cancel();

          await showGeneralDialog(
            context: context,
            barrierDismissible: false,
            barrierLabel: "Success Dialog",
            transitionDuration: const Duration(milliseconds: 400),
            pageBuilder: (context, animation, secondaryAnimation) {
              return _VerificationSuccessDialog(
                onDismiss: () => Navigator.of(context).pop(),
              );
            },
            transitionBuilder: (context, animation, secondaryAnimation, child) {
              return ScaleTransition(
                scale: CurvedAnimation(
                  parent: animation,
                  curve: Curves.easeOutBack,
                ),
                child: FadeTransition(opacity: animation, child: child),
              );
            },
          );

          if (mounted) {
            setState(() {
              _registerStep = 3;
            });
          }
        }
      } catch (e) {
        setState(() => _isLoading = false);
        if (mounted) {
          DialogService().showError('Error: ${e.toString()}');
        }
      }
    }
    // Step 3: Password - Create Firebase Account + Firestore doc
    else if (_registerStep == 3) {
      _checkPasswordRequirements();

      if (!_hasMinLength ||
          !_hasUppercase ||
          !_hasLowercase ||
          !_hasNumber ||
          !_passwordsMatch) {
        setState(() => _showPasswordErrors = true);
        return;
      }

      setState(() => _isLoading = true);

      try {
        if (_pendingGoogleAccount != null) {
          // Google user -> Sign into Firebase now
          debugPrint(
            '🔥 OTP verified -> Now creating Firebase Auth for Google user',
          );
          final wrapper = GoogleSignInWrapper.instance;
          final userCredential = await wrapper.signInToFirebase(
            _pendingGoogleAccount!,
          );

          if (userCredential?.user == null) {
            throw Exception('Gagal masuk ke Firebase dengan akun Google');
          }

          // Link email/password
          await firebaseService.linkEmailPassword(
            _emailController.text.trim().toLowerCase(),
            _passwordRegisterController.text,
          );

          // Create Firestore document with profile data from Step 0
          debugPrint('📝 Creating Firestore document for Google user...');
          await firebaseService.createUserDocument(
            userCredential!.user!,
            name: _nameController.text.trim(),
            phone: _phoneController.text.trim(),
          );
          debugPrint('✅ Firestore document created for Google user');

          _pendingGoogleAccount = null;

          setState(() {
            _isLoading = false;
            _registerStep = 4;
          });
        } else {
          // Email user -> Create new Firebase account
          final credential = await firebaseService.registerWithEmail(
            _emailController.text.trim().toLowerCase(),
            _passwordRegisterController.text,
          );

          if (credential?.user != null) {
            // Create Firestore document with profile data from Step 0
            debugPrint('📝 Creating Firestore document for email user...');
            await firebaseService.createUserDocument(
              credential!.user!,
              name: _nameController.text.trim(),
              phone: _phoneController.text.trim(),
            );
            debugPrint('✅ Firestore document created for email user');

            setState(() {
              _isLoading = false;
              _registerStep = 4;
            });
          } else {
            throw Exception('Gagal membuat akun');
          }
        }
      } catch (e) {
        setState(() => _isLoading = false);
        if (mounted) {
          String errorMessage = e.toString();
          if (errorMessage.contains('email-already-in-use')) {
            errorMessage =
                'Email sudah terdaftar. Silakan login atau gunakan email lain.';
          } else if (errorMessage.contains('provider-already-linked')) {
            setState(() {
              _registerStep = 4;
            });
            return;
          }
          DialogService().showError('Gagal: $errorMessage');
        }
      }
    }
  }

  /// Send verification OTP via chosen method (email or WhatsApp)
  Future<void> _sendVerificationOTP(String method) async {
    setState(() {
      _verificationMethod = method;
      _isLoading = true;
    });

    try {
      bool otpSent;
      String targetDisplay;

      if (method == 'wa') {
        otpSent = await FonnteService.sendOTP(_phoneController.text.trim());
        targetDisplay = _phoneController.text.trim();
      } else {
        otpSent = await EmailJSService.sendOTP(_emailController.text.trim());
        targetDisplay = _emailController.text.trim();
      }

      if (otpSent) {
        setState(() {
          _isLoading = false;
          _registerStep = 2;
        });
        _startTimer();

        if (mounted) {
          final channel = method == 'wa' ? 'WhatsApp' : 'Email';
          DialogService().showInfo(
            'Kode verifikasi telah dikirim ke $channel ($targetDisplay)',
          );
        }
      } else {
        throw Exception('Gagal mengirim kode verifikasi');
      }
    } catch (e) {
      setState(() => _isLoading = false);
      if (mounted) {
        DialogService().showError('Gagal: ${e.toString()}');
      }
    }
  }

  Future<void> _resendCode() async {
    setState(() => _isLoading = true);

    try {
      bool otpSent;

      if (_verificationMethod == 'wa') {
        otpSent = await FonnteService.sendOTP(_phoneController.text.trim());
      } else {
        otpSent = await EmailJSService.sendOTP(_emailController.text.trim());
      }

      if (mounted) {
        setState(() => _isLoading = false);

        if (otpSent) {
          for (var c in _codeControllers) {
            c.clear();
          }
          _startTimer();
          final channel = _verificationMethod == 'wa' ? 'WhatsApp' : 'Email';
          DialogService().showSuccess(
            'Kode verifikasi baru telah dikirim ke $channel Anda',
          );
        } else {
          DialogService().showError('Gagal mengirim kode verifikasi');
        }
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isLoading = false);
        DialogService().showError('Gagal mengirim ulang: ${e.toString()}');
      }
    }
  }

  /// Send OTP for forgot password flow
  Future<void> _sendForgotPasswordOTP(String method) async {
    setState(() {
      _verificationMethod = method;
      _isLoading = true;
    });

    try {
      bool otpSent;
      String targetDisplay;

      if (method == 'wa') {
        // For WhatsApp, we need phone number - get from user data
        final userData = await FirebaseService().getUserDataByEmail(
          _emailController.text.trim(),
        );
        if (userData?.phoneNumber == null) {
          throw Exception(
            'Nomor WhatsApp tidak terdaftar. Gunakan verifikasi email.',
          );
        }
        otpSent = await FonnteService.sendOTP(userData!.phoneNumber!);
        targetDisplay = userData.phoneNumber!;
      } else {
        otpSent = await EmailJSService.sendOTP(_emailController.text.trim());
        targetDisplay = _emailController.text.trim();
      }

      if (otpSent) {
        setState(() {
          _isLoading = false;
          _forgotPasswordStep = 2; // Go to OTP verification
        });
        _startTimer();

        if (mounted) {
          final channel = method == 'wa' ? 'WhatsApp' : 'Email';
          DialogService().showInfo(
            'Kode verifikasi telah dikirim ke $channel ($targetDisplay)',
          );
        }
      } else {
        throw Exception('Gagal mengirim kode verifikasi');
      }
    } catch (e) {
      setState(() => _isLoading = false);
      if (mounted) {
        DialogService().showError('Gagal: ${e.toString()}');
      }
    }
  }

  /// Verify OTP for forgot password
  Future<void> _handleForgotPasswordVerification() async {
    final code = _codeControllers.map((c) => c.text).join();

    if (code.length != 5) {
      DialogService().showError('Masukkan kode 5 digit');
      return;
    }

    setState(() => _isLoading = true);

    try {
      bool isVerified;

      if (_verificationMethod == 'wa') {
        final userData = await FirebaseService().getUserDataByEmail(
          _emailController.text.trim(),
        );
        isVerified = FonnteService.verifyOTP(userData?.phoneNumber ?? '', code);
      } else {
        isVerified = EmailJSService.verifyOTP(
          _emailController.text.trim(),
          code,
        );
      }

      if (isVerified) {
        setState(() {
          _isLoading = false;
          _forgotPasswordStep = 3; // Go to new password step
        });
        _timer?.cancel();
      } else {
        setState(() {
          _isLoading = false;
          _isCodeError = true;
        });

        // Auto-reset error state after 3 seconds
        _errorTimer?.cancel();
        _errorTimer = Timer(const Duration(seconds: 3), () {
          if (mounted) {
            setState(() => _isCodeError = false);
          }
        });

        DialogService().showError('Kode verifikasi salah');
      }
    } catch (e) {
      setState(() => _isLoading = false);
      if (mounted) {
        DialogService().showError('Verifikasi gagal: ${e.toString()}');
      }
    }
  }

  /// Resend OTP for forgot password
  Future<void> _resendForgotPasswordCode() async {
    setState(() => _isLoading = true);

    try {
      bool otpSent;

      if (_verificationMethod == 'wa') {
        final userData = await FirebaseService().getUserDataByEmail(
          _emailController.text.trim(),
        );
        otpSent = await FonnteService.sendOTP(userData?.phoneNumber ?? '');
      } else {
        otpSent = await EmailJSService.sendOTP(_emailController.text.trim());
      }

      if (mounted) {
        setState(() => _isLoading = false);

        if (otpSent) {
          for (var c in _codeControllers) {
            c.clear();
          }
          _startTimer();
          final channel = _verificationMethod == 'wa' ? 'WhatsApp' : 'Email';
          DialogService().showSuccess(
            'Kode verifikasi baru telah dikirim ke $channel Anda',
          );
        } else {
          DialogService().showError('Gagal mengirim kode verifikasi');
        }
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isLoading = false);
        DialogService().showError('Gagal mengirim ulang: ${e.toString()}');
      }
    }
  }

  /// Handle password reset after OTP verification
  Future<void> _handlePasswordReset() async {
    setState(() => _isLoading = true);

    try {
      final email = _emailController.text.trim().toLowerCase();

      // Kirim email reset password via Firebase — cara resmi & benar
      await FirebaseService().resetPassword(email);

      if (mounted) {
        setState(() {
          _isLoading = false;
          _forgotPasswordStep = 4; // Tampilkan halaman sukses
        });
      }
    } catch (e) {
      setState(() => _isLoading = false);
      if (mounted) {
        DialogService().showError('Gagal mereset password: ${e.toString()}');
      }
    }
  }

  Future<void> _signInWithGoogle() async {
    setState(() => _isGoogleLoading = true);

    try {
      final firebaseService = FirebaseService();
      final wrapper = GoogleSignInWrapper.instance;

      // Step 1: Get Google account info - ONE picker popup only
      final googleAccount = await wrapper.getGoogleAccount();
      if (googleAccount == null) {
        if (mounted) setState(() => _isGoogleLoading = false);
        return; // User canceled
      }

      debugPrint('📧 Google account selected: ${googleAccount.email}');

      // Step 2: Check if email is already registered in Firestore BEFORE signing into Firebase
      bool isRegistered = await firebaseService.checkEmailExists(googleAccount.email);

      if (mounted) {
        if (isRegistered) {
          // RETURNING USER -> Safe to sign in to Firebase
          final result = await wrapper.signInToFirebase(googleAccount);
          if (result?.user == null) {
            if (mounted) setState(() => _isGoogleLoading = false);
            return;
          }

          final userData = await firebaseService.getUserData(result!.user!.uid);

          if (mounted) {
            if (userData == null || !userData.isSetupComplete) {
              Navigator.of(context).pushReplacement(
                MaterialPageRoute(
                  builder: (context) => const EarlySetupScreen(),
                ),
              );
            } else {
              Navigator.of(context).pushReplacement(
                MaterialPageRoute(builder: (context) => const HomeScreen()),
              );
            }
          }
        } else {
          // NEW USER -> DO NOT register automatically. Redirect to Register form.
          debugPrint('🆕 Unregistered Google user -> Redirecting to Registration Form');
          
          // Save Google account for later (after OTP verification & form completion)
          _pendingGoogleAccount = googleAccount;
          _emailController.text = googleAccount.email;
          _nameController.text = googleAccount.displayName ?? '';

          setState(() {
            _isRegistering = true;
            _isForgotPassword = false;
            _registerStep = 0;
            _isGoogleLoading = false;
          });

          DialogService().showSuccess(
            'Silahkan lengkapi registrasi terlebih dahulu.',
          );
        }
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isGoogleLoading = false);
        DialogService().showError('Login gagal: ${e.toString()}');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final screenHeight = MediaQuery.of(context).size.height;

    return Scaffold(
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
        child: Stack(
          children: [
            // Main Column with Header and Form
            Column(
              children: [
                // Header Section with Overlay Image
                _buildHeader(screenHeight),

                // Spacer for form overlap
                const SizedBox(height: 0),
              ],
            ),

            // Visible curved shadow element behind card (white transparent)
            Positioned(
              top: screenHeight * 0.30 - 45,
              left: 20,
              right: 20,
              child: Container(
                height: 50,
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.4),
                  borderRadius: const BorderRadius.vertical(
                    top: Radius.circular(24),
                  ),
                ),
              ),
            ),

            // Form Section (overlapping the header)
            Column(
              children: [
                SizedBox(height: screenHeight * 0.30 - 24),
                _buildFormSection(),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildHeader(double screenHeight) {
    return Container(
      height: screenHeight * 0.30,
      width: double.infinity,
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [headerGradientStart, headerGradientEnd],
        ),
      ),
      child: Stack(
        children: [
          // Overlay Image - positioned lower and centered
          Positioned(
            top: 20,
            left: 0,
            right: 0,
            bottom: -20,
            child: Opacity(
              opacity: 0.30,
              child: Image.asset(
                'assets/images/overlayimage.png',
                fit: BoxFit.contain,
                alignment: Alignment.center,
              ),
            ),
          ),

          // Text Content with Shadows
          Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const SizedBox(height: 30),

                // App Name "Amori" - with shadow
                Text(
                  'Amori',
                  style: TextStyle(
                    fontFamily: 'Poppins',
                    fontSize: 48,
                    fontWeight: FontWeight.w600,
                    color: Colors.white,
                    letterSpacing: 1,
                    height: 1.1,
                    shadows: [
                      Shadow(
                        color: Colors.black.withOpacity(0.3),
                        blurRadius: 8,
                        offset: const Offset(0, 4),
                      ),
                    ],
                  ),
                ),

                // Subtitle "Assistant" - with shadow
                Text(
                  'Assistant',
                  style: TextStyle(
                    fontFamily: 'Poppins',
                    fontSize: 20,
                    fontWeight: FontWeight.w300,
                    color: Colors.white.withOpacity(0.9),
                    letterSpacing: 3,
                    shadows: [
                      Shadow(
                        color: Colors.black.withOpacity(0.25),
                        blurRadius: 6,
                        offset: const Offset(0, 3),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFormSection() {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.15),
            blurRadius: 20,
            offset: const Offset(0, -10),
            spreadRadius: 0,
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.fromLTRB(24, 32, 24, 24),
        child: AnimatedSwitcher(
          duration: const Duration(milliseconds: 300),
          transitionBuilder: (Widget child, Animation<double> animation) {
            return FadeTransition(opacity: animation, child: child);
          },
          child: Column(
            key: ValueKey<String>(
              _isForgotPassword
                  ? 'forgot_pass'
                  : (_isRegistering ? 'reg_$_registerStep' : 'login'),
            ),
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              // Back button for Register/Forgot Password modes
              if (_isRegistering || _isForgotPassword)
                Align(
                  alignment: Alignment.centerLeft,
                  child: IconButton(
                    icon: const Icon(Icons.arrow_back, color: primaryBrown),
                    onPressed: () => _showCancelConfirmationDialog(),
                    padding: EdgeInsets.zero,
                    constraints: const BoxConstraints(),
                  ),
                ),
              if (_isRegistering || _isForgotPassword)
                const SizedBox(height: 8),
              // Welcome Text with Toggle Logic - Show for all steps except success
              if (!(_isRegistering && _registerStep == 4) &&
                  !(_isForgotPassword && _forgotPasswordStep == 3)) ...[
                Text(
                  _isForgotPassword
                      ? (_forgotPasswordStep == 0
                            ? 'Lupa Password?'
                            : (_forgotPasswordStep == 1
                                  ? 'Verifikasi Email'
                                  : 'Reset Password'))
                      : (_isRegistering
                            ? (_registerStep == 0
                                  ? 'Lengkapi Profil'
                                  : (_registerStep == 1
                                        ? 'Pilih Verifikasi'
                                        : (_registerStep == 2
                                              ? 'Verifikasi Kode'
                                              : 'Buat Kata Sandi')))
                            : 'Selamat Datang'),
                  style: const TextStyle(
                    fontFamily: 'Poppins',
                    fontSize: 28,
                    fontWeight: FontWeight.w700,
                    color: primaryBrown,
                  ),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 8),
                Text(
                  _isForgotPassword
                      ? (_forgotPasswordStep == 0
                            ? 'Masukan email terdaftar untuk reset password'
                            : (_forgotPasswordStep == 1
                                  ? 'Silahkan masukan kode verifikasi yang dikirimkan ke email'
                                  : 'Masukan password baru untuk melanjutkan'))
                      : (_isRegistering
                            ? (_registerStep == 0
                                  ? 'Lengkapi informasi profil untuk registrasi'
                                  : (_registerStep == 1
                                        ? 'Pilih metode verifikasi yang Anda inginkan'
                                        : (_registerStep == 2
                                              ? 'Masukkan kode verifikasi yang telah dikirim'
                                              : 'Buat password yang kuat untuk akun anda')))
                            : 'Masukan Detail Login Kamu'),
                  style: TextStyle(
                    fontFamily: 'Poppins',
                    fontSize: 14,
                    fontWeight: FontWeight.w400,
                    color: primaryBrown.withOpacity(0.7),
                  ),
                  textAlign: TextAlign.center,
                ),
              ],

              const SizedBox(height: 32),

              // Form Content Toggle
              // Form Content Toggle
              if (_isForgotPassword)
                _buildForgotPasswordContent()
              else if (_isRegistering)
                _buildRegisterContent()
              else
                _buildLoginContent(),

              const SizedBox(height: 24),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildLoginContent() {
    return Form(
      key: _formKey,
      autovalidateMode: _autoValidateMode,
      child: Column(
        children:
            [
                  // Email Field
                  _buildInputField(
                    controller: _emailController,
                    label: 'Alamat Email',
                    hintText: 'Masukkan email anda',
                    keyboardType: TextInputType.emailAddress,
                    onChanged: (_) {
                      if (_loginEmailError != null) {
                        setState(() => _loginEmailError = null);
                      }
                    },
                    errorText: _loginEmailError,
                  ),
                  const SizedBox(height: 16),

                  // Password Field
                  _buildInputField(
                    controller: _passwordController,
                    label: 'Kata Sandi',
                    hintText: '••••••••••',
                    obscureText: _obscurePassword,
                    suffixIcon: IconButton(
                      icon: Icon(
                        _obscurePassword
                            ? Icons.visibility_outlined
                            : Icons.visibility_off_outlined,
                        color: primaryBrown.withOpacity(0.5),
                      ),
                      onPressed: () =>
                          setState(() => _obscurePassword = !_obscurePassword),
                    ),
                    onChanged: (_) {
                      if (_loginPasswordError != null) {
                        setState(() => _loginPasswordError = null);
                      }
                    },
                    errorText: _loginPasswordError,
                  ),
                  const SizedBox(height: 30),

                  // Login Button
                  _buildGradientButton(
                    text: 'Login',
                    onPressed: _isLoading ? null : _signInWithEmail,
                    isLoading: _isLoading,
                  ),
                  const SizedBox(height: 16),

                  // Toggle to Register using Outline Button Style
                  _buildOutlinedButton(
                    text: 'Register',
                    onPressed: _toggleAuthMode,
                  ),
                  const SizedBox(height: 16),

                  // Forgot Password
                  // Forgot Password
                  Align(
                    alignment: Alignment.centerRight,
                    child: TextButton(
                      onPressed: _toggleForgotPasswordMode,
                      style: TextButton.styleFrom(
                        padding: EdgeInsets.zero,
                        minimumSize: Size.zero,
                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        foregroundColor: primaryBrown.withOpacity(0.7),
                        overlayColor: primaryBrown.withOpacity(0.1),
                      ),
                      child: Text(
                        'Lupa Password ?',
                        style: TextStyle(
                          fontFamily: 'Poppins',
                          fontSize: 12,
                          color: primaryBrown.withOpacity(0.7),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(height: 24),

                  // Divider with text
                  Row(
                    children: [
                      Expanded(
                        child: Divider(color: primaryBrown.withOpacity(0.2)),
                      ),
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 16),
                        child: Text(
                          'Atau Login Menggunakan',
                          style: TextStyle(
                            fontFamily: 'Poppins',
                            fontSize: 12,
                            color: primaryBrown.withOpacity(0.5),
                          ),
                        ),
                      ),
                      Expanded(
                        child: Divider(color: primaryBrown.withOpacity(0.2)),
                      ),
                    ],
                  ),
                  const SizedBox(height: 24),
                  _buildGoogleButton(),
                ]
                .animate(interval: 50.ms)
                .fadeIn(duration: 300.ms)
                .slideY(
                  begin: 0.1,
                  end: 0,
                  duration: 300.ms,
                  curve: Curves.easeOut,
                ),
      ),
    );
  }

  Widget _buildRegisterContent() {
    return Column(
      children: [
        if (_registerStep == 0) ...[
          // Step 0: Profile - Name, Phone, Email
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 24.0),
            child: Image.asset(
              'assets/images/registerletter5.gif',
              height: 180,
              fit: BoxFit.contain,
            ),
          ),
          _buildInputField(
            controller: _nameController,
            label: 'Nama Lengkap',
            hintText: 'Masukkan nama lengkap anda',
            onChanged: (_) {
              if (_nameError != null) {
                setState(() => _nameError = null);
              }
            },
            errorText: _nameError,
          ),
          const SizedBox(height: 16),
          _buildInputField(
            controller: _phoneController,
            label: 'Nomor Telepon',
            hintText: 'Contoh: 081234567890',
            keyboardType: TextInputType.phone,
            onChanged: (_) {
              if (_phoneError != null) {
                setState(() => _phoneError = null);
              }
            },
            errorText: _phoneError,
          ),
          const SizedBox(height: 16),
          _buildInputField(
            controller: _emailController,
            label: 'Alamat Email',
            hintText: 'Masukkan email anda',
            keyboardType: TextInputType.emailAddress,
            onChanged: (_) {
              if (_emailError != null) {
                setState(() => _emailError = null);
              }
            },
            errorText: _emailError,
          ),
          const SizedBox(height: 20),
          _buildGradientButton(
            text: 'Lanjutkan',
            onPressed: _isLoading ? null : _handleRegister,
            isLoading: _isLoading,
          ),
        ] else if (_registerStep == 1) ...[
          // Step 1: Choose Verification Method
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 24.0),
            child: Image.asset(
              'assets/images/registerletter.gif',
              height: 180,
              fit: BoxFit.contain,
            ),
          ),
          // Email verification button
          _buildVerificationMethodButton(
            icon: Icons.email_outlined,
            title: 'Verifikasi via Email',
            subtitle: _emailController.text.trim(),
            onTap: _isLoading ? null : () => _sendVerificationOTP('email'),
          ),
          const SizedBox(height: 16),
          // WhatsApp verification button
          _buildVerificationMethodButton(
            icon: Icons.chat_outlined,
            title: 'Verifikasi via WhatsApp',
            subtitle: _phoneController.text.trim(),
            onTap: _isLoading ? null : () => _sendVerificationOTP('wa'),
            isWhatsApp: true,
          ),
          if (_isLoading) ...[
            const SizedBox(height: 24),
            const Center(
              child: CircularProgressIndicator(
                color: primaryBrown,
                strokeWidth: 2,
              ),
            ),
          ],
        ] else if (_registerStep == 2) ...[
          // Step 2: Verification OTP - Using shared widget
          VerificationStepWidget(
            codeControllers: _codeControllers,
            isError: _isCodeError,
            onErrorReset: () => setState(() => _isCodeError = false),
            remainingSeconds: _remainingSeconds,
            formattedTime: _formattedTime,
            isLoading: _isLoading,
            onVerify: _handleRegister,
            onResend: _resendCode,
            onChangeEmail: () => setState(() => _registerStep = 1),
            buttonBuilder: (text, onPressed, isLoading) => _buildGradientButton(
              text: text,
              onPressed: onPressed,
              isLoading: isLoading,
            ),
          ),
        ] else if (_registerStep == 3) ...[
          // Step 3: Create Password
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 24.0),
            child: Image.asset(
              'assets/images/registerletter4.gif',
              height: 180,
              fit: BoxFit.contain,
            ),
          ),
          _buildInputField(
            controller: _passwordRegisterController,
            label: 'Buat Kata Sandi',
            hintText: '••••••••••',
            obscureText: _obscurePassword,
            onChanged: (_) => _checkPasswordRequirements(),
            suffixIcon: IconButton(
              icon: Icon(
                _obscurePassword
                    ? Icons.visibility_outlined
                    : Icons.visibility_off_outlined,
                color: primaryBrown.withOpacity(0.5),
              ),
              onPressed: () =>
                  setState(() => _obscurePassword = !_obscurePassword),
            ),
            errorText:
                (_showPasswordErrors ||
                        _passwordRegisterController.text.isNotEmpty) &&
                    (!_hasMinLength ||
                        !_hasUppercase ||
                        !_hasLowercase ||
                        !_hasNumber)
                ? _getPasswordErrorText()
                : null,
          ),
          const SizedBox(height: 8),
          // Password Requirements
          Align(
            alignment: Alignment.centerLeft,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildPasswordRequirementRow(
                  'Minimal 8 karakter',
                  _hasMinLength,
                ),
                const SizedBox(height: 6),
                _buildPasswordRequirementRow(
                  'Huruf besar (A-Z)',
                  _hasUppercase,
                ),
                const SizedBox(height: 6),
                _buildPasswordRequirementRow(
                  'Huruf kecil (a-z)',
                  _hasLowercase,
                ),
                const SizedBox(height: 6),
                _buildPasswordRequirementRow('Angka (0-9)', _hasNumber),
              ],
            ),
          ),

          const SizedBox(height: 16),
          _buildInputField(
            controller: _confirmPasswordController,
            label: 'Konfirmasi Kata Sandi',
            hintText: '••••••••••',
            obscureText: _obscurePassword,
            onChanged: (_) {
              setState(() {
                _passwordsMatch =
                    _passwordRegisterController.text ==
                    _confirmPasswordController.text;
              });
            },
            errorText: _showPasswordErrors && !_passwordsMatch
                ? 'Kata sandi tidak cocok'
                : null,
          ),
          const SizedBox(height: 20),
          _buildGradientButton(
            text: 'Daftar Sekarang',
            onPressed: _isLoading ? null : _handleRegister,
            isLoading: _isLoading,
          ),
        ] else ...[
          // Step 4: Success
          const SizedBox(height: 24),
          Image.asset(
            'assets/images/registerletter3.gif',
            height: 180,
            fit: BoxFit.contain,
          ),
          const SizedBox(height: 24),
          const Text(
            'Registrasi Berhasil',
            style: TextStyle(
              fontFamily: 'Poppins',
              fontSize: 24,
              fontWeight: FontWeight.bold,
              color: primaryBrown,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 8),
          Text(
            'Akun anda telah berhasil dibuat.\nSilahkan login untuk melanjutkan.',
            style: TextStyle(
              fontFamily: 'Poppins',
              fontSize: 14,
              color: primaryBrown.withOpacity(0.7),
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 40),
          _buildGradientButton(
            text: 'Lanjut ke Login',
            onPressed: _toggleAuthMode,
          ),
        ],

        // Back to Login Link (Only for Steps 0-3)
        if (_registerStep != 4) ...[
          const SizedBox(height: 16),
          TextButton(
            onPressed: _toggleAuthMode,
            child: const Text(
              'Kembali ke Login',
              style: TextStyle(color: primaryBrown, fontFamily: 'Poppins'),
            ),
          ),
        ],
      ],
    );
  }

  /// Build a verification method selection button
  Widget _buildVerificationMethodButton({
    required IconData icon,
    required String title,
    required String subtitle,
    required VoidCallback? onTap,
    bool isWhatsApp = false,
  }) {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(16),
        child: Container(
          width: double.infinity,
          padding: const EdgeInsets.all(20),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(16),
            border: Border.all(color: primaryBrown.withOpacity(0.15)),
            boxShadow: [
              BoxShadow(
                color: primaryBrown.withOpacity(0.05),
                blurRadius: 10,
                offset: const Offset(0, 4),
              ),
            ],
          ),
          child: Row(
            children: [
              Container(
                width: 52,
                height: 52,
                decoration: BoxDecoration(
                  color: isWhatsApp
                      ? const Color(0xFF25D366).withOpacity(0.1)
                      : primaryBrown.withOpacity(0.08),
                  borderRadius: BorderRadius.circular(14),
                ),
                child: Icon(
                  icon,
                  color: isWhatsApp ? const Color(0xFF25D366) : primaryBrown,
                  size: 26,
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      title,
                      style: const TextStyle(
                        fontFamily: 'Poppins',
                        fontSize: 15,
                        fontWeight: FontWeight.w600,
                        color: primaryBrown,
                      ),
                    ),
                    const SizedBox(height: 2),
                    Text(
                      subtitle,
                      style: TextStyle(
                        fontFamily: 'Poppins',
                        fontSize: 12,
                        color: primaryBrown.withOpacity(0.5),
                      ),
                    ),
                  ],
                ),
              ),
              Icon(
                Icons.arrow_forward_ios_rounded,
                color: primaryBrown.withOpacity(0.3),
                size: 18,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildInputField({
    required TextEditingController controller,
    required String label,
    String? hintText,
    bool obscureText = false,
    TextInputType? keyboardType,
    Widget? suffixIcon,
    String? Function(String?)? validator,
    void Function(String)? onChanged,
    String? errorText,
  }) {
    final bool hasError = errorText != null && errorText.isNotEmpty;

    return Builder(
      builder: (context) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            TextFormField(
              controller: controller,
              obscureText: obscureText,
              keyboardType: keyboardType,
              onChanged: onChanged,
              onTap: () {
                Future.delayed(const Duration(milliseconds: 300), () {
                  if (context.mounted) {
                    Scrollable.ensureVisible(
                      context,
                      alignment: 0.45,
                      duration: const Duration(milliseconds: 300),
                      curve: Curves.easeInOut,
                    );
                  }
                });
              },
              style: const TextStyle(
                fontFamily: 'Poppins',
                fontSize: 14,
                color: primaryBrown,
              ),
              decoration: InputDecoration(
                labelText: label,
                hintText: hintText,
                labelStyle: TextStyle(
                  fontFamily: 'Poppins',
                  fontSize: 12,
                  color: hasError ? Colors.red : primaryBrown.withOpacity(0.6),
                ),
                hintStyle: TextStyle(
                  fontFamily: 'Poppins',
                  fontSize: 14,
                  color: primaryBrown.withOpacity(0.4),
                ),
                suffixIcon: suffixIcon,
                filled: true,
                fillColor: Colors.white,
                contentPadding: const EdgeInsets.fromLTRB(16, 16, 16, 12),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(12),
                  borderSide: BorderSide(
                    color: hasError
                        ? Colors.red
                        : primaryBrown.withOpacity(0.15),
                  ),
                ),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(12),
                  borderSide: BorderSide(
                    color: hasError
                        ? Colors.red
                        : primaryBrown.withOpacity(0.15),
                    width: hasError ? 1.5 : 1,
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(12),
                  borderSide: BorderSide(
                    color: hasError
                        ? Colors.red
                        : primaryBrown.withOpacity(0.4),
                    width: hasError ? 1.5 : 1,
                  ),
                ),
              ),
              validator: validator,
            ),
            if (hasError) ...[
              const SizedBox(height: 4),
              Padding(
                padding: const EdgeInsets.only(left: 4),
                child: Text(
                  errorText,
                  style: const TextStyle(
                    fontFamily: 'Poppins',
                    fontSize: 11,
                    color: Colors.red,
                  ),
                ),
              ),
            ],
          ],
        );
      },
    );
  }

  Widget _buildGradientButton({
    required String text,
    VoidCallback? onPressed,
    bool isLoading = false,
  }) {
    return ScaleButton(
      onPressed: isLoading ? null : onPressed,
      child: Container(
        width: double.infinity,
        height: 52,
        decoration: BoxDecoration(
          gradient: const LinearGradient(
            colors: [lightBrown, headerGradientEnd],
          ),
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: primaryBrown.withOpacity(0.3),
              blurRadius: 8,
              offset: const Offset(0, 4),
            ),
          ],
        ),
        child: ElevatedButton(
          onPressed: isLoading ? null : onPressed,
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.transparent,
            shadowColor: Colors.transparent,
            foregroundColor: Colors.white,
            overlayColor: Colors.white.withOpacity(0.2),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
          ),
          child: isLoading
              ? const SizedBox(
                  width: 20,
                  height: 20,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                  ),
                )
              : Text(
                  text,
                  style: const TextStyle(
                    fontFamily: 'Poppins',
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Colors.white,
                  ),
                ),
        ),
      ),
    );
  }

  Widget _buildOutlinedButton({required String text, VoidCallback? onPressed}) {
    return Container(
      width: double.infinity,
      height: 52,
      decoration: BoxDecoration(
        color: const Color(0xFFD9D9D9),
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: primaryBrown.withOpacity(0.1),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: TextButton(
        onPressed: onPressed,
        style: TextButton.styleFrom(
          foregroundColor: primaryBrown,
          overlayColor: primaryBrown.withOpacity(0.15),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
        child: Text(
          text,
          style: TextStyle(
            fontFamily: 'Poppins',
            fontSize: 16,
            fontWeight: FontWeight.w600,
            color: primaryBrown.withOpacity(0.85),
          ),
        ),
      ),
    );
  }

  Widget _buildGoogleButton() {
    return Stack(
      clipBehavior: Clip.none,
      children: [
        // Shadow behind button (offset to top) with outline
        Positioned(
          top: -6,
          left: 0,
          right: -6,
          bottom: 6,
          child: Container(
            width: 180,
            height: 48,
            decoration: BoxDecoration(
              color: primaryBrown.withOpacity(0.5),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(
                color: primaryBrown.withOpacity(0.5),
                width: 0.5,
              ),
            ),
          ),
        ),
        // Main button
        Container(
          width: 180,
          height: 48,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(12),
            border: Border.all(
              color: primaryBrown.withOpacity(0.5),
              width: 0.5,
            ),
          ),
          child: TextButton(
            onPressed: _isGoogleLoading ? null : _signInWithGoogle,
            style: TextButton.styleFrom(
              foregroundColor: primaryBrown,
              overlayColor: primaryBrown.withOpacity(0.1),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // Google Icon from reliable CDN with smooth fade-in
                Image.network(
                  'https://developers.google.com/identity/images/g-logo.png',
                  width: 20,
                  height: 20,
                  gaplessPlayback: true,
                  frameBuilder:
                      (context, child, frame, wasSynchronouslyLoaded) {
                        if (wasSynchronouslyLoaded) return child;
                        return AnimatedOpacity(
                          duration: const Duration(milliseconds: 200),
                          opacity: frame == null ? 0 : 1,
                          child: child,
                        );
                      },
                  errorBuilder: (context, error, stackTrace) {
                    // Fallback to colored G if network fails
                    return Container(
                      width: 20,
                      height: 20,
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: const Color(0xFF4285F4),
                          width: 2,
                        ),
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: const Center(
                        child: Text(
                          'G',
                          style: TextStyle(
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                            color: Color(0xFF4285F4),
                          ),
                        ),
                      ),
                    );
                  },
                ),
                const SizedBox(width: 12),
                Text(
                  'Google',
                  style: TextStyle(
                    fontFamily: 'Poppins',
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                    color: primaryBrown.withOpacity(0.85),
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildForgotPasswordContent() {
    switch (_forgotPasswordStep) {
      case 0:
        return _buildForgotEmailStep();
      case 1:
        return _buildForgotChooseVerificationStep();
      case 2:
        return _buildForgotVerifyOTPStep();
      case 3:
        return _buildForgotNewPasswordStep();
      case 4:
        return _buildForgotSuccessStep();
      default:
        return _buildForgotEmailStep();
    }
  }

  Widget _buildForgotEmailStep() {
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 24.0),
          child: Image.asset(
            'assets/images/registerletter.gif',
            height: 180,
            fit: BoxFit.contain,
          ),
        ),
        _buildInputField(
          controller: _emailController,
          label: 'E-mail',
          hintText: 'Masukan email terdaftar',
          keyboardType: TextInputType.emailAddress,
          onChanged: (_) {
            if (_emailError != null) {
              setState(() => _emailError = null);
            }
          },
          errorText: _emailError,
        ),
        const SizedBox(height: 30),
        _buildGradientButton(
          text: 'Lanjutkan',
          onPressed: _isLoading
              ? null
              : () async {
                  if (_emailController.text.trim().isEmpty) {
                    setState(() => _emailError = 'Email tidak boleh kosong');
                    return;
                  }
                  if (!RegExp(
                    r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$',
                  ).hasMatch(_emailController.text.trim())) {
                    setState(() => _emailError = 'Email tidak valid');
                    return;
                  }

                  setState(() => _isLoading = true);

                  try {
                    // Check if email exists in Firebase
                    final email = _emailController.text.trim();
                    final userExists = await FirebaseService().checkEmailExists(
                      email,
                    );

                    if (!userExists) {
                      if (mounted) {
                        setState(() => _isLoading = false);
                        DialogService().showError(
                          'Email tidak terdaftar. Silakan daftar terlebih dahulu.',
                        );
                      }
                      return;
                    }

                    if (mounted) {
                      setState(() {
                        _isLoading = false;
                        _forgotPasswordStep = 1; // Go to choose verification
                      });
                    }
                  } catch (e) {
                    setState(() => _isLoading = false);
                    if (mounted) {
                      DialogService().showError(
                        'Terjadi kesalahan: ${e.toString()}',
                      );
                    }
                  }
                },
          isLoading: _isLoading,
        ),
        const SizedBox(height: 16),
        _buildOutlinedButton(
          text: 'Kembali ke Login',
          onPressed: _toggleForgotPasswordMode,
        ),
      ],
    );
  }

  Widget _buildForgotChooseVerificationStep() {
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 24.0),
          child: Image.asset(
            'assets/images/registerletter2.gif',
            height: 180,
            fit: BoxFit.contain,
          ),
        ),
        // Email verification button
        _buildVerificationMethodButton(
          icon: Icons.email_outlined,
          title: 'Verifikasi via Email',
          subtitle: _emailController.text.trim(),
          onTap: _isLoading ? null : () => _sendForgotPasswordOTP('email'),
        ),
        const SizedBox(height: 16),
        // WhatsApp verification button (optional - if user has phone)
        _buildVerificationMethodButton(
          icon: Icons.chat_outlined,
          title: 'Verifikasi via WhatsApp',
          subtitle: 'Kirim kode ke WhatsApp',
          onTap: _isLoading ? null : () => _sendForgotPasswordOTP('wa'),
          isWhatsApp: true,
        ),
        if (_isLoading) ...[
          const SizedBox(height: 24),
          const Center(
            child: CircularProgressIndicator(
              color: primaryBrown,
              strokeWidth: 2,
            ),
          ),
        ],
        const SizedBox(height: 16),
        _buildOutlinedButton(
          text: 'Kembali',
          onPressed: () => setState(() => _forgotPasswordStep = 0),
        ),
      ],
    );
  }

  Widget _buildForgotVerifyOTPStep() {
    return VerificationStepWidget(
      codeControllers: _codeControllers,
      isError: _isCodeError,
      onErrorReset: () => setState(() => _isCodeError = false),
      remainingSeconds: _remainingSeconds,
      formattedTime: _formattedTime,
      isLoading: _isLoading,
      onVerify: _handleForgotPasswordVerification,
      onResend: _resendForgotPasswordCode,
      onChangeEmail: () => setState(() => _forgotPasswordStep = 1),
      buttonBuilder: (text, onPressed, isLoading) => _buildGradientButton(
        text: text,
        onPressed: onPressed,
        isLoading: isLoading,
      ),
    );
  }

  Widget _buildForgotNewPasswordStep() {
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 24.0),
          child: Image.asset(
            'assets/images/registerletter4.gif',
            height: 180,
            fit: BoxFit.contain,
          ),
        ),
        _buildInputField(
          controller: _passwordRegisterController,
          label: 'Password Baru',
          hintText: '••••••••••',
          obscureText: _obscurePassword,
          onChanged: (_) => _checkPasswordRequirements(),
          suffixIcon: IconButton(
            icon: Icon(
              _obscurePassword
                  ? Icons.visibility_outlined
                  : Icons.visibility_off_outlined,
              color: primaryBrown.withOpacity(0.5),
            ),
            onPressed: () =>
                setState(() => _obscurePassword = !_obscurePassword),
          ),
          errorText:
              (_showPasswordErrors ||
                      _passwordRegisterController.text.isNotEmpty) &&
                  (!_hasMinLength ||
                      !_hasUppercase ||
                      !_hasLowercase ||
                      !_hasNumber)
              ? _getPasswordErrorText()
              : null,
        ),
        const SizedBox(height: 8),
        // Password Requirements
        Align(
          alignment: Alignment.centerLeft,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildPasswordRequirementRow('Minimal 8 karakter', _hasMinLength),
              const SizedBox(height: 6),
              _buildPasswordRequirementRow('Huruf besar (A-Z)', _hasUppercase),
              const SizedBox(height: 6),
              _buildPasswordRequirementRow('Huruf kecil (a-z)', _hasLowercase),
              const SizedBox(height: 6),
              _buildPasswordRequirementRow('Angka (0-9)', _hasNumber),
            ],
          ),
        ),
        const SizedBox(height: 16),
        _buildInputField(
          controller: _confirmPasswordController,
          label: 'Konfirmasi Password',
          hintText: '••••••••••',
          obscureText: _obscurePassword,
          onChanged: (_) => _checkPasswordRequirements(),
          suffixIcon: IconButton(
            icon: Icon(
              _obscurePassword
                  ? Icons.visibility_outlined
                  : Icons.visibility_off_outlined,
              color: primaryBrown.withOpacity(0.5),
            ),
            onPressed: () =>
                setState(() => _obscurePassword = !_obscurePassword),
          ),
          errorText:
              _confirmPasswordController.text.isNotEmpty && !_passwordsMatch
              ? 'Password tidak cocok'
              : null,
        ),
        const SizedBox(height: 30),
        _buildGradientButton(
          text: 'Reset Password',
          onPressed:
              (_isLoading ||
                  !_hasMinLength ||
                  !_hasUppercase ||
                  !_hasLowercase ||
                  !_hasNumber ||
                  !_passwordsMatch)
              ? null
              : _handlePasswordReset,
          isLoading: _isLoading,
        ),
        const SizedBox(height: 16),
        _buildOutlinedButton(
          text: 'Kembali',
          onPressed: () => setState(() => _forgotPasswordStep = 2),
        ),
      ],
    );
  }

  Widget _buildForgotSuccessStep() {
    return Column(
      children: [
        const SizedBox(height: 40),
        Image.asset(
          'assets/images/registerletter3.gif',
          height: 150,
          fit: BoxFit.contain,
        ),
        const SizedBox(height: 32),
        const Text(
          'Email Reset Password Terkirim!',
          textAlign: TextAlign.center,
          style: TextStyle(
            fontFamily: 'Poppins',
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: primaryBrown,
          ),
        ),
        const SizedBox(height: 8),
        const Text(
          'Link reset password telah dikirim ke email Anda.\nBuka email → klik link → buat password baru → lalu login.',
          textAlign: TextAlign.center,
          style: TextStyle(
            fontFamily: 'Poppins',
            fontSize: 14,
            color: Colors.grey,
          ),
        ),
        const SizedBox(height: 40), // Spacer before button
        _buildGradientButton(
          text: 'Lanjut ke Login',
          onPressed: () {
            _toggleForgotPasswordMode();
          },
        ),
      ],
    );
  }

  Widget _buildPasswordRequirementRow(String text, bool met) {
    return Row(
      children: [
        Container(
          padding: const EdgeInsets.all(2),
          decoration: BoxDecoration(
            color: met ? Colors.green : Colors.grey.withOpacity(0.2),
            shape: BoxShape.circle,
          ),
          child: Icon(
            Icons.check,
            size: 10,
            color: met ? Colors.white : Colors.grey,
          ),
        ),
        const SizedBox(width: 8),
        Text(
          text,
          style: TextStyle(
            fontFamily: 'Poppins',
            fontSize: 12,
            color: met ? Colors.green : Colors.grey,
            fontWeight: met ? FontWeight.w500 : FontWeight.normal,
          ),
        ),
      ],
    );
  }
}

class _VerificationSuccessDialog extends StatefulWidget {
  final VoidCallback onDismiss;

  const _VerificationSuccessDialog({required this.onDismiss});

  @override
  State<_VerificationSuccessDialog> createState() =>
      _VerificationSuccessDialogState();
}

class _VerificationSuccessDialogState
    extends State<_VerificationSuccessDialog> {
  int _countdown = 5;
  Timer? _timer;

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

  void _startCountdown() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (mounted) {
        setState(() {
          if (_countdown > 1) {
            _countdown--;
          } else {
            timer.cancel();
            widget.onDismiss();
          }
        });
      }
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      backgroundColor: Colors.white,
      surfaceTintColor: Colors.white,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
      contentPadding: const EdgeInsets.all(24),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Image.asset(
            'assets/images/registerletter3.gif',
            height: 150,
            fit: BoxFit.contain,
          ),
          const SizedBox(height: 16),
          const Text(
            'Email Berhasil Diverifikasi!',
            style: TextStyle(
              fontFamily: 'Poppins',
              fontWeight: FontWeight.bold,
              fontSize: 18,
              color: primaryBrown,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 8),
          const Text(
            'Silahkan melanjutkan proses registrasi.',
            style: TextStyle(
              fontFamily: 'Poppins',
              fontSize: 14,
              color: Colors.black87,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 24),
          // Custom Gradient Button
          Stack(
            clipBehavior: Clip.none,
            children: [
              // Shadow behind button (offset to top)
              Positioned(
                top: -6,
                left: 0,
                right: -6,
                bottom: 6,
                child: Container(
                  width: double.infinity,
                  height: 45,
                  decoration: BoxDecoration(
                    color: primaryBrown.withOpacity(0.3),
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
              ),
              // Main button
              Container(
                width: double.infinity,
                height: 45,
                decoration: BoxDecoration(
                  gradient: const LinearGradient(
                    colors: [lightBrown, headerGradientEnd],
                  ),
                  borderRadius: BorderRadius.circular(12),
                  boxShadow: [
                    BoxShadow(
                      color: primaryBrown.withOpacity(0.2),
                      blurRadius: 8,
                      offset: const Offset(0, 4),
                    ),
                  ],
                ),
                child: ElevatedButton(
                  onPressed: widget.onDismiss,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.transparent,
                    shadowColor: Colors.transparent,
                    foregroundColor: Colors.white,
                    overlayColor: Colors.white.withOpacity(0.2),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: const Text(
                    'Lanjut isi Password',
                    style: TextStyle(
                      fontFamily: 'Poppins',
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ],
          ),

          const SizedBox(height: 32),
          Text(
            'Otomatis lanjut dalam $_countdown detik',
            style: TextStyle(
              fontFamily: 'Poppins',
              fontSize: 12,
              color: Colors.grey,
              fontStyle: FontStyle.italic,
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }
}
