import 'package:flutter/material.dart';
import 'package:kmobile/data/repositories/auth_repository.dart';
import 'package:kmobile/features/profile/change_password/change_password_screen.dart';
import 'package:kmobile/features/profile/logout_dialog.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../di/injection.dart';
import '../../l10n/app_localizations.dart';
import 'package:kmobile/features/profile/preferences/preference_screen.dart';

class ProfileScreen extends StatefulWidget {
  final String mobileNumber;
  const ProfileScreen({super.key, required this.mobileNumber});

  @override
  State<ProfileScreen> createState() => _ProfileScreenState();
}

class _ProfileScreenState extends State<ProfileScreen> {
    Future<void> _handleLogout(BuildContext context) async {
    final auth = getIt<AuthRepository>();
    final prefs = await SharedPreferences.getInstance();
    await prefs.clear(); // clear saved session/token
    await auth.clearAuthTokens();
    // Navigate to login and remove all previous routes
    Navigator.pushNamedAndRemoveUntil(context, '/login', (route) => false);
  }

  @override
  Widget build(BuildContext context) {
    final loc = AppLocalizations.of(context);

    return Scaffold(
      appBar: AppBar(
        title: Text(loc.profile), // Localized "Profile"
      ),
      body: ListView(
        children: [
          ListTile(
            leading: const Icon(Icons.settings),
            title: Text(loc.preferences), 
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => const PreferenceScreen()),
              );
            },
          ),
          ListTile(
            leading: const Icon(Icons.password),
            title: Text(loc.changeLoginPassword), 
            onTap: () {
            Navigator.push(  
              context,
            MaterialPageRoute(builder: (context) => ChangePasswordScreen(
              mobileNumber: widget.mobileNumber,
            )),
            );
            },
          ),
          ListTile(
            leading: const Icon(Icons.logout),
            title: Text(AppLocalizations.of(context).logout), 
            onTap: () async {
              final shouldLogout = await showDialog<bool>(
                context: context,
                builder: (_) => const LogoutDialog(),
              );

              if (shouldLogout == true) {
                await _handleLogout(context);
              }
            },
          ),
          // You can add more profile options here later
        ],
      ),
    );
  }
}
