import 'dart:async';
import 'package:flutter/material.dart';
import '../../data/models/souscription_status_model.dart';
import '../../../../features/authentication/presentation/bloc/auth_bloc.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

/// Étape 5 — En attente de validation SuperAdmin
class AwaitingValidationPage extends StatefulWidget {
  final SouscriptionStatusModel? souscription;

  const AwaitingValidationPage({super.key, this.souscription});

  @override
  State<AwaitingValidationPage> createState() => _AwaitingValidationPageState();
}

class _AwaitingValidationPageState extends State<AwaitingValidationPage>
    with SingleTickerProviderStateMixin {
  late AnimationController _pulseController;
  late Animation<double> _pulseAnimation;
  Timer? _refreshTimer;

  @override
  void initState() {
    super.initState();
    _pulseController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    )..repeat(reverse: true);
    _pulseAnimation = Tween(begin: 0.85, end: 1.0).animate(
      CurvedAnimation(parent: _pulseController, curve: Curves.easeInOut),
    );

    // Vérification périodique toutes les 30 secondes (re-check le statut)
    _refreshTimer = Timer.periodic(const Duration(seconds: 30), (_) {
      if (mounted) {
        context.read<AuthBloc>().add(const AuthStatusChecked());
      }
    });
  }

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

  @override
  Widget build(BuildContext context) {
    final sosc = widget.souscription;
    return Scaffold(
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // Animation d'attente
              ScaleTransition(
                scale: _pulseAnimation,
                child: Container(
                  width: 120,
                  height: 120,
                  decoration: BoxDecoration(
                    color: const Color(0xFFFFF3E0),
                    shape: BoxShape.circle,
                    border: Border.all(color: const Color(0xFFF57C00), width: 3),
                  ),
                  child: const Icon(
                    Icons.hourglass_top_rounded,
                    size: 60,
                    color: Color(0xFFF57C00),
                  ),
                ),
              ),
              const SizedBox(height: 32),

              const Text(
                'Demande soumise !',
                style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 12),
              const Text(
                'Votre souscription est en cours de vérification par notre équipe. '
                'Vous recevrez une notification dès que votre compte sera activé.',
                style: TextStyle(fontSize: 15, color: Colors.grey, height: 1.5),
                textAlign: TextAlign.center,
              ),

              if (sosc != null) ...[
                const SizedBox(height: 32),
                _SummaryCard(souscription: sosc),
              ],

              const SizedBox(height: 32),
              const Text(
                'Cette vérification prend généralement 24 à 48 heures ouvrables.',
                style: TextStyle(fontSize: 13, color: Colors.grey),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 24),

              OutlinedButton.icon(
                onPressed: () =>
                    context.read<AuthBloc>().add(const AuthStatusChecked()),
                icon: const Icon(Icons.refresh),
                label: const Text('Vérifier l\'état de mon compte'),
              ),

              const SizedBox(height: 12),
              TextButton(
                onPressed: () =>
                    context.read<AuthBloc>().add(const AuthLogoutRequested()),
                child: const Text('Se déconnecter'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _SummaryCard extends StatelessWidget {
  final SouscriptionStatusModel souscription;
  const _SummaryCard({required this.souscription});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Column(
        children: [
          _Row('Organisation', souscription.organisationNom ?? '—'),
          _Row('Formule', souscription.typeFormule),
          _Row('Période', souscription.typePeriode),
          if (souscription.montantTotal != null)
            _Row('Montant payé', '${souscription.montantTotal!.toStringAsFixed(0)} FCFA'),
        ],
      ),
    );
  }
}

class _Row extends StatelessWidget {
  final String label;
  final String value;
  const _Row(this.label, this.value);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label, style: const TextStyle(color: Colors.grey, fontSize: 13)),
          Text(value,
              style: const TextStyle(fontWeight: FontWeight.w500, fontSize: 13)),
        ],
      ),
    );
  }
}
