import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../auth_provider.dart';
import 'package:environment_monitoring_app/services/api_service.dart'; // Import ApiService for typing

class ForgotPasswordScreen extends StatefulWidget {
  @override
  State<ForgotPasswordScreen> createState() => _ForgotPasswordScreenState();
}

class _ForgotPasswordScreenState extends State<ForgotPasswordScreen> {
  final _formKey = GlobalKey<FormState>();
  String email = '';
  String message = '';

  @override
  Widget build(BuildContext context) {
    final auth = Provider.of<AuthProvider>(context);
    // FIX: Retrieve ApiService from the Provider tree
    final apiService = Provider.of<ApiService>(context, listen: false);

    return Scaffold(
      appBar: AppBar(title: Text("Forgot Password")),
      body: Padding(
        padding: const EdgeInsets.all(24),
        child: Form(
          key: _formKey,
          child: ListView(
            children: [
              Text("Reset Password", style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold)),
              SizedBox(height: 32),
              TextFormField(
                decoration: InputDecoration(labelText: "Email"),
                keyboardType: TextInputType.emailAddress,
                onChanged: (val) => email = val,
                validator: (val) => val == null || val.isEmpty ? "Enter your email" : null,
              ),
              SizedBox(height: 24),
              ElevatedButton(
                onPressed: () {
                  if (_formKey.currentState!.validate()) {
                    // FIX: Use the retrieved ApiService instance for the post call via AuthProvider
                    // Note: AuthProvider's resetPassword method still uses its internal _apiService field.
                    // This is an architectural inconsistency (using Provider for one service but not others inside AuthProvider)
                    // but the immediate fix for this screen is to ensure the resetPassword method works.
                    // Since AuthProvider's resetPassword method uses its internal, injected _apiService, we can call it directly.
                    auth.resetPassword(email);
                    setState(() => message = "Reset link sent to $email");
                  }
                },
                child: Text("Send Reset Link"),
              ),
              if (message.isNotEmpty)
                Padding(
                  padding: const EdgeInsets.only(top: 12),
                  child: Text(message, style: TextStyle(color: Colors.green)),
                ),
              SizedBox(height: 24),
              TextButton(
                onPressed: () => Navigator.pushReplacementNamed(context, '/'),
                child: Text("Back to Login"),
              ),
            ],
          ),
        ),
      ),
    );
  }
}