import 'dart:async';
import 'package:flutter/material.dart';

import '../config/app_school.dart';
import '../services/auth_storage.dart';
import 'login_page.dart';
import 'home_page.dart';

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

  @override
  State<SplashPage> createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  // rosso bordeaux ripreso dal cuore del logo YogaSoul
  static const Color kRed = Color(0xFFB01E28);

  Timer? _timer;
  int _seconds = 5; // countdown iniziale

  // Evita doppie navigazioni: countdown, tap e sblocco possono
  // altrimenti innescare più push.
  bool _navigated = false;

  @override
  void initState() {
    super.initState();
    _timer = Timer.periodic(const Duration(seconds: 1), (t) {
      if (!mounted) return;
      setState(() => _seconds--);
      if (_seconds <= 0) {
        t.cancel();
        _finishSplash();
      }
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  // Fine dello splash: prova lo sblocco, poi instrada.
  Future<void> _finishSplash() async {
    if (_navigated) return;

    final outcome = await AuthStorage.instance.tryUnlockAtStartup();
    if (!mounted || _navigated) return;

    switch (outcome.result) {
      case UnlockResult.success:
        _navigated = true;
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (_) => HomePage(
              token: outcome.token!,
              school: kYogaSoulSchool,
              userFirstName: null,
            ),
          ),
        );
        break;
      case UnlockResult.noSavedLogin:
      case UnlockResult.biometricFailed:
      case UnlockResult.biometricUnavailable:
        _goToLogin();
        break;
    }
  }

  // Tap sullo schermo: salta il countdown ma passa comunque dallo sblocco.
  void _onTapSkip() {
    if (_navigated) return;
    _timer?.cancel();
    _finishSplash();
  }

  void _goToLogin() {
    if (_navigated || !mounted) return;
    _navigated = true;
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(builder: (_) => const LoginPage()),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: _onTapSkip,
        child: Stack(
          fit: StackFit.expand,
          children: [
            // ---- Foto di sfondo full-screen
            Image.asset('assets/images/splash_bg.png', fit: BoxFit.cover),

            // ---- Contenuto (logo + testo) in alto
            SafeArea(
              child: Padding(
                padding: const EdgeInsets.fromLTRB(24, 10, 24, 24),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    const SizedBox(height: 8),

                    // Logo YogaSoul
                    Image.asset(
                      'assets/images/yogasoul_logo.png',
                      height: 72,
                      fit: BoxFit.contain,
                    ),

                    const SizedBox(height: 26),

                    // ---- Blocco testo su velo bianco morbido per leggibilità
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 18,
                        vertical: 16,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.white.withOpacity(0.42),
                        borderRadius: BorderRadius.circular(20),
                      ),
                      child: Column(
                        children: [
                          const Text(
                            'Il tuo spazio.',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontSize: 30,
                              height: 1.1,
                              fontWeight: FontWeight.w900,
                              color: Color(0xFF1F1F1F),
                            ),
                          ),
                          const Text(
                            'La tua energia.',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontSize: 30,
                              height: 1.1,
                              fontWeight: FontWeight.w900,
                              color: kRed,
                            ),
                          ),

                          const SizedBox(height: 14),

                          const Text(
                            'Ti diamo il benvenuto in YogiBook,\n'
                            'l’app della scuola YogaSoul — Seregno.\n'
                            'Ti accompagna nelle tue lezioni e nei tuoi pacchetti.',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontSize: 14,
                              height: 1.4,
                              fontWeight: FontWeight.w600,
                              color: Color(0xFF2A2A2A),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),

            // ---- Logo YogiBook + countdown in basso
            Positioned(
              left: 0,
              right: 0,
              bottom: 30,
              child: Column(
                children: [
                  Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 16,
                      vertical: 10,
                    ),
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.75),
                      borderRadius: BorderRadius.circular(16),
                    ),
                    child: Image.asset(
                      'assets/images/yogibook_logo.png',
                      height: 40,
                      fit: BoxFit.contain,
                    ),
                  ),
                  const SizedBox(height: 14),
                  Container(
                    width: 40,
                    height: 40,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: Colors.white.withValues(alpha: 0.25),
                      border: Border.all(color: Colors.white, width: 1.5),
                    ),
                    child: Text(
                      '$_seconds',
                      style: const TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.w900,
                        fontSize: 18,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
