import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../bloc/onboarding_bloc.dart';
import '../../data/models/souscription_status_model.dart';

/// Étape 4 — Lancement du paiement Wave + attente du retour
class WavePaymentPage extends StatefulWidget {
  final SouscriptionStatusModel souscription;
  final String waveLaunchUrl;

  const WavePaymentPage({
    super.key,
    required this.souscription,
    required this.waveLaunchUrl,
  });

  @override
  State<WavePaymentPage> createState() => _WavePaymentPageState();
}

class _WavePaymentPageState extends State<WavePaymentPage>
    with WidgetsBindingObserver {
  bool _paymentLaunched = false;
  bool _appResumed = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // Quand l'utilisateur revient dans l'app après Wave
    if (state == AppLifecycleState.resumed && _paymentLaunched && !_appResumed) {
      _appResumed = true;
      context.read<OnboardingBloc>().add(const OnboardingRetourDepuisWave());
    }
  }

  Future<void> _lancerWave() async {
    final uri = Uri.parse(widget.waveLaunchUrl);
    if (await canLaunchUrl(uri)) {
      setState(() => _paymentLaunched = true);
      await launchUrl(uri, mode: LaunchMode.externalApplication);
    } else {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Impossible d\'ouvrir Wave. Vérifiez que l\'application est installée.'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final montant = widget.souscription.montantTotal ?? 0;

    return Scaffold(
      appBar: AppBar(
        title: const Text('Paiement Wave'),
        automaticallyImplyLeading: false,
      ),
      body: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // Logo Wave stylisé
            Container(
              width: 100,
              height: 100,
              decoration: BoxDecoration(
                color: const Color(0xFF00B9F1),
                borderRadius: BorderRadius.circular(24),
              ),
              child: const Icon(Icons.waves, color: Colors.white, size: 52),
            ),
            const SizedBox(height: 32),

            const Text(
              'Paiement par Wave',
              style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 8),
            Text(
              'Montant : ${montant.toStringAsFixed(0)} FCFA',
              style: const TextStyle(fontSize: 18, color: Colors.grey),
            ),
            const SizedBox(height: 32),

            if (!_paymentLaunched) ...[
              const Text(
                'Cliquez sur le bouton ci-dessous pour ouvrir Wave et effectuer votre paiement.',
                textAlign: TextAlign.center,
                style: TextStyle(color: Colors.grey),
              ),
              const SizedBox(height: 24),
              ElevatedButton.icon(
                onPressed: _lancerWave,
                icon: const Icon(Icons.open_in_new),
                label: const Text('Ouvrir Wave'),
                style: ElevatedButton.styleFrom(
                  minimumSize: const Size(200, 52),
                  backgroundColor: const Color(0xFF00B9F1),
                  foregroundColor: Colors.white,
                ),
              ),
            ] else ...[
              const Icon(Icons.hourglass_top, size: 40, color: Colors.orange),
              const SizedBox(height: 16),
              const Text(
                'Paiement en cours dans Wave…\nRevenez ici une fois le paiement effectué.',
                textAlign: TextAlign.center,
                style: TextStyle(color: Colors.grey),
              ),
              const SizedBox(height: 24),
              OutlinedButton(
                onPressed: () => context.read<OnboardingBloc>().add(
                      const OnboardingRetourDepuisWave(),
                    ),
                child: const Text('J\'ai effectué le paiement'),
              ),
              const SizedBox(height: 12),
              TextButton(
                onPressed: _lancerWave,
                child: const Text('Rouvrir Wave'),
              ),
            ],
          ],
        ),
      ),
    );
  }
}
