import 'package:flutter/material.dart';

import '../services/auth_service.dart';
import '../services/password_reset_service.dart';
import '../widgets/app_logo.dart';
import '../widgets/auth_card.dart';
import '../widgets/primary_button.dart';
import 'reset_password_screen.dart';

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

  static const routeName = '/forgot-password';

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

class _ForgotPasswordScreenState extends State<ForgotPasswordScreen> {
  final _formKey = GlobalKey<FormState>();
  final _emailController = TextEditingController();
  final _passwordResetService = PasswordResetService();
  bool _loading = false;
  String? _message;
  bool _success = false;

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

  Future<void> _submit() async {
    FocusScope.of(context).unfocus();
    if (!_formKey.currentState!.validate()) return;

    setState(() {
      _loading = true;
      _message = null;
      _success = false;
    });

    try {
      final email = _emailController.text.trim();
      final resetRequest = await _passwordResetService.forgotPassword(email);

      if (!mounted) return;
      if (resetRequest.hasToken) {
        Navigator.pushReplacementNamed(
          context,
          ResetPasswordScreen.routeName,
          arguments: ResetPasswordArguments(
            email: email,
            token: resetRequest.token!,
          ),
        );
        return;
      }

      setState(() {
        _success = true;
        _message =
            'Instruksi reset password telah dikirim jika email terdaftar.';
      });
    } on AuthException catch (exception) {
      setState(() => _message = exception.message);
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final colors = Theme.of(context).colorScheme;

    return Scaffold(
      body: DecoratedBox(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [Color(0xFFE3F1F8), Color(0xFFEAF6FF), Color(0xFFF6FAFD)],
          ),
        ),
        child: SafeArea(
          child: Center(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(24),
              child: ConstrainedBox(
                constraints: const BoxConstraints(maxWidth: 460),
                child: AuthCard(
                  children: [
                    const Center(child: AppLogo(size: 68)),
                    const SizedBox(height: 20),
                    Text(
                      'Lupa Password',
                      textAlign: TextAlign.center,
                      style:
                          Theme.of(context).textTheme.headlineSmall?.copyWith(
                                fontWeight: FontWeight.w900,
                                color: const Color(0xFF0B1F33),
                              ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      'Masukkan email Anda untuk menerima instruksi reset password.',
                      textAlign: TextAlign.center,
                      style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                            color: colors.onSurfaceVariant,
                            height: 1.45,
                          ),
                    ),
                    const SizedBox(height: 24),
                    Form(
                      key: _formKey,
                      child: TextFormField(
                        controller: _emailController,
                        keyboardType: TextInputType.emailAddress,
                        decoration: const InputDecoration(
                          prefixIcon: Icon(Icons.alternate_email_rounded),
                          labelText: 'Email',
                        ),
                        validator: (value) {
                          final text = value?.trim() ?? '';
                          if (!text.contains('@')) {
                            return 'Masukkan alamat email yang valid.';
                          }
                          return null;
                        },
                      ),
                    ),
                    if (_message != null) ...[
                      const SizedBox(height: 16),
                      Text(
                        _message!,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: _success ? colors.primary : colors.error,
                          fontWeight: FontWeight.w700,
                        ),
                      ),
                    ],
                    const SizedBox(height: 22),
                    PrimaryButton(
                      label: _loading ? 'Mengirim...' : 'Kirim Tautan Reset',
                      icon: Icons.mark_email_read_rounded,
                      onPressed: _loading ? null : _submit,
                    ),
                    const SizedBox(height: 14),
                    TextButton(
                      onPressed: _loading ? null : () => Navigator.pop(context),
                      child: const Text('Kembali ke Halaman Masuk'),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
