import 'dart:convert';
import 'package:autos/core/theme/app_theme.dart';
import 'package:autos/core/theme/app_typography.dart';
import 'package:autos/data/models/user_model.dart';
import 'package:autos/presentation/providers/user_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';

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

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

class _ForgotPasswordScreenState extends ConsumerState<ForgotPasswordScreen> {
  final emailController = TextEditingController();
  final _storage = const FlutterSecureStorage();
  static const _userKey = 'logged_in_user'; // same key as in UserNotifier

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

  Future<void> _loadSavedEmail() async {
    final jsonString = await _storage.read(key: _userKey);
    if (jsonString != null) {
      try {
        final userData = jsonDecode(jsonString);
        final user = UserModel.fromJson(userData);
        if (user.email.isNotEmpty) {
          setState(() => emailController.text = user.email);
        }
      } catch (_) {
        // ignore corrupted data, keep field empty
      }
    }
  }

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

  @override
  Widget build(BuildContext context) {
    final userState = ref.watch(userProvider);

    return Scaffold(
      appBar: AppBar(
        title: Text("Forgot Password", style: AppTypo.h3),
        backgroundColor: AppTheme.primary,
        iconTheme: Theme.of(context).appBarTheme.iconTheme,
      ),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Center(
          child: SingleChildScrollView(
            child: Column(
              children: [
                const Text(
                  "Reset your password",
                  style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 20),
                const Text(
                  "Enter your registered email address. We’ll send you a reset link.",
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.black54),
                ),
                const SizedBox(height: 40),
                TextField(
                  controller: emailController,
                  decoration: const InputDecoration(
                    labelText: "Email",
                    prefixIcon: Icon(Icons.email_outlined),
                    border: OutlineInputBorder(),
                  ),
                ),
                const SizedBox(height: 30),
                userState.isLoading
                    ? const CircularProgressIndicator()
                    : ElevatedButton(
                        onPressed: () async {
                          final email = emailController.text.trim();
                          if (email.isEmpty) {
                            Fluttertoast.showToast(
                              msg: "Please enter your email address",
                              backgroundColor: Colors.red,
                            );
                            return;
                          }

                          try {
                            await ref
                                .read(userProvider.notifier)
                                .sendPasswordResetLink(email);

                            Fluttertoast.showToast(
                              msg: "Reset link sent to $email",
                              backgroundColor: Colors.green,
                              toastLength: Toast.LENGTH_LONG,
                            );
                            Navigator.pop(context);
                          } catch (e) {
                            Fluttertoast.showToast(
                              msg: "Failed to send reset link: $e",
                              backgroundColor: Colors.red,
                            );
                          }
                        },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: AppTheme.primary,
                          minimumSize: const Size(double.infinity, 50),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(40),
                          ),
                        ),
                        child: const Text(
                          "Send Reset Link",
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: Colors.white,
                          ),
                        ),
                      ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
