import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:monitoring/screens/login_screen.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SplashScreen extends StatefulWidget {
  final Function(String token, Map<String, dynamic> user) onLoginSuccess;

  const SplashScreen({super.key, required this.onLoginSuccess});

  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  bool isLoading = true;

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

  Future<void> checkLoginStatus() async {
    final prefs = await SharedPreferences.getInstance();
    final token = prefs.getString('token');
    final userJson = prefs.getString('user');

    if (token != null && userJson != null) {
      final user = jsonDecode(userJson);
      widget.onLoginSuccess(token, Map<String, dynamic>.from(user));
    } else {
      setState(() => isLoading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading) {
      return const Scaffold(body: Center(child: CircularProgressIndicator()));
    }

    return Scaffold(
      appBar: AppBar(title: const Text('Santri App')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (_) => LoginScreen(onLoginSuccess: widget.onLoginSuccess),
              ),
            );
          },
          child: const Text('Login as Santri'),
        ),
      ),
    );
  }
}
