import 'package:flutter/material.dart';

import '../models/app_user.dart';
import '../services/auth_service.dart';
import '../widgets/app_logo.dart';
import 'dashboard_screen.dart';
import 'login_screen.dart';

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

  static const routeName = '/';

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

class _SplashScreenState extends State<SplashScreen> {
  final AuthService _authService = AuthService();

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

  Future<void> _bootstrap() async {
    await Future<void>.delayed(const Duration(milliseconds: 700));

    AppUser? user;
    try {
      debugPrint('[Splash] Mulai cek session/profile...');
      user = await _authService.profile().timeout(
            const Duration(seconds: 10),
            onTimeout: () => null,
          );
      debugPrint(
        '[Splash] Cek session selesai. Login tersimpan: ${user != null}',
      );
    } on AuthException catch (exception) {
      debugPrint('[Splash] Auth gagal: ${exception.message}');
      await _authService.clearSession();
      user = null;
    } catch (error) {
      debugPrint('[Splash] Bootstrap error: $error');
      user = null;
    }

    if (!mounted) return;
    Navigator.pushReplacementNamed(
      context,
      user == null ? LoginScreen.routeName : DashboardScreen.routeName,
      arguments: user,
    );
  }

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: DecoratedBox(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [Color(0xFFD9EEF8), Color(0xFFEAF6FF), Color(0xFFF6FAFD)],
          ),
        ),
        child: Center(
          child: AppLogo(size: 96, showText: true),
        ),
      ),
    );
  }
}
