import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';

import '../../config/app_router.dart';
import '../../services/auth_service.dart';
import '../../services/reprise_session.dart';

/// Point d'entrée `/reprise?token=` — charge le dossier et ouvre le wizard (#112).
class RepriseEntryScreen extends StatefulWidget {
  final String? token;

  const RepriseEntryScreen({super.key, this.token});

  @override
  State<RepriseEntryScreen> createState() => _RepriseEntryScreenState();
}

class _RepriseEntryScreenState extends State<RepriseEntryScreen> {
  bool _loading = true;
  String? _error;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) => _load());
  }

  Future<void> _load() async {
    final token = widget.token?.trim() ?? '';
    if (token.isEmpty) {
      setState(() {
        _loading = false;
        _error = 'Lien invalide ou expiré.';
      });
      return;
    }

    setState(() {
      _loading = true;
      _error = null;
    });

    try {
      final dossier = await AuthService.getRepriseDossier(token);
      if (!mounted) return;

      RepriseSession.clear();
      RepriseSession.start(token: token, dossier: dossier);

      if (dossier.isParent) {
        RepriseSession.applyToParent(userRegistrationDataNotifier, dossier);
        context.go('/parent-register-step1');
        return;
      }
      if (dossier.isAm) {
        RepriseSession.applyToAm(amRegistrationDataNotifier, dossier);
        context.go('/am-register-step1');
        return;
      }

      RepriseSession.clear();
      setState(() {
        _loading = false;
        _error = 'Type de dossier non pris en charge pour la reprise.';
      });
    } catch (e) {
      if (!mounted) return;
      RepriseSession.clear();
      setState(() {
        _loading = false;
        _error = e is Exception
            ? e.toString().replaceFirst('Exception: ', '')
            : 'Impossible de charger votre dossier.';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          Positioned.fill(
            child: Image.asset(
              'assets/images/paper2.png',
              fit: BoxFit.cover,
              repeat: ImageRepeat.repeat,
            ),
          ),
          Center(
            child: ConstrainedBox(
              constraints: const BoxConstraints(maxWidth: 420),
              child: Padding(
                padding: const EdgeInsets.all(24),
                child: _buildBody(),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBody() {
    if (_loading) {
      return Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const CircularProgressIndicator(),
          const SizedBox(height: 20),
          Text(
            'Chargement de votre dossier…',
            style: GoogleFonts.merienda(fontSize: 16),
            textAlign: TextAlign.center,
          ),
        ],
      );
    }

    final err = _error ?? 'Lien invalide ou expiré.';
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(Icons.error_outline, size: 48, color: Colors.red.shade700),
        const SizedBox(height: 16),
        Text(
          'Reprise du dossier',
          style: GoogleFonts.merienda(
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 12),
        Text(
          err,
          style: GoogleFonts.merienda(fontSize: 14, color: Colors.black87),
          textAlign: TextAlign.center,
        ),
        const SizedBox(height: 24),
        TextButton(
          onPressed: () => context.go('/login'),
          child: Text(
            'Retour à la connexion',
            style: GoogleFonts.merienda(
              decoration: TextDecoration.underline,
              color: const Color(0xFF2D6A4F),
            ),
          ),
        ),
      ],
    );
  }
}
