import 'package:flutter/material.dart';
import '../../../core/services/auth_proxy_service.dart';
import '../../../core/ui/toast_service.dart';
import 'package:userfront/i18n.dart';

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

  @override
  State<ForgotPasswordScreen> createState() => _ForgotPasswordScreenState();
}

class _ForgotPasswordScreenState extends State<ForgotPasswordScreen> {
  final TextEditingController _loginIdController = TextEditingController();
  bool _isLoading = false;
  bool _drySendEnabled = false;

  @override
  void initState() {
    super.initState();
    _drySendEnabled =
        _parseBoolParam(Uri.base.queryParameters['drySend']) &&
        !AuthProxyService.isProdEnv;
  }

  Future<void> _handlePasswordReset() async {
    final input = _loginIdController.text.trim();
    if (input.isEmpty) {
      _showError(tr('msg.userfront.forgot.input_required'));
      return;
    }

    String loginId = input;
    if (!input.contains('@')) {
      // Format phone number if it's not an email
      loginId = input.replaceAll(RegExp(r'[-\s]'), '');
      if (loginId.startsWith('010')) {
        loginId = '+82${loginId.substring(1)}';
      }
    }

    setState(() => _isLoading = true);

    try {
      await AuthProxyService.initiatePasswordReset(
        loginId,
        drySend: _drySendEnabled,
      );
      if (mounted) {
        ToastService.success(tr('msg.userfront.forgot.sent'));
        Navigator.of(context).pop();
      }
    } catch (e) {
      if (mounted) {
        _showError(
          tr('msg.userfront.forgot.error', params: {'error': e.toString()}),
        );
      }
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  void _showError(String message) {
    ToastService.error(message);
  }

  bool _parseBoolParam(String? value) {
    if (value == null) {
      return false;
    }
    final normalized = value.toLowerCase();
    return normalized == 'true' || normalized == '1' || normalized == 'yes';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(tr('ui.userfront.forgot.title')),
        centerTitle: true,
      ),
      body: Center(
        child: Container(
          constraints: const BoxConstraints(maxWidth: 400),
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Text(
                tr('ui.userfront.forgot.heading'),
                style: const TextStyle(
                  fontSize: 28,
                  fontWeight: FontWeight.bold,
                ),
                textAlign: TextAlign.center,
              ),
              if (_drySendEnabled) ...[
                const SizedBox(height: 12),
                Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 12,
                    vertical: 10,
                  ),
                  decoration: BoxDecoration(
                    color: const Color(0xFFFFF3CD),
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(color: const Color(0xFFFFC107)),
                  ),
                  child: Row(
                    children: [
                      const Icon(
                        Icons.warning_amber_rounded,
                        color: Color(0xFF8A6D3B),
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          tr('msg.userfront.forgot.dry_send'),
                          style: const TextStyle(
                            color: Color(0xFF8A6D3B),
                            fontSize: 12,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
              const SizedBox(height: 16),
              Text(
                tr('msg.userfront.forgot.description'),
                textAlign: TextAlign.center,
                style: const TextStyle(color: Colors.grey),
              ),
              const SizedBox(height: 40),
              TextField(
                controller: _loginIdController,
                decoration: InputDecoration(
                  labelText: tr('ui.userfront.forgot.input_label'),
                  border: const OutlineInputBorder(),
                  prefixIcon: const Icon(Icons.person_outline),
                ),
                onSubmitted: (_) => _handlePasswordReset(),
              ),
              const SizedBox(height: 24),
              FilledButton(
                onPressed: _isLoading ? null : _handlePasswordReset,
                style: FilledButton.styleFrom(
                  minimumSize: const Size.fromHeight(50),
                ),
                child: _isLoading
                    ? const SizedBox(
                        height: 20,
                        width: 20,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          color: Colors.white,
                        ),
                      )
                    : Text(tr('ui.userfront.forgot.submit')),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
