import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/chat/chat_opening_provider.dart';
import '../../../core/theme/halo_tokens.dart';
import '../state/payment_draft_provider.dart';

/// Single point of truth for the discount-vs-method-pick branch.
///
/// Reads `chat-pricing.first_session_discount.eligible`. When the customer
/// is eligible (and the discount is enabled), routes to the S6 paywall;
/// otherwise routes to the regular method-pick screen. The draft is reset
/// here so a fresh entry into the flow always starts clean.
class PaymentEntryScreen extends ConsumerStatefulWidget {
  const PaymentEntryScreen({super.key});

  @override
  ConsumerState<PaymentEntryScreen> createState() => _PaymentEntryScreenState();
}

class _PaymentEntryScreenState extends ConsumerState<PaymentEntryScreen> {
  bool _routed = false;

  @override
  void initState() {
    super.initState();
    Future.microtask(() {
      if (!mounted) return;
      ref.read(paymentDraftNotifierProvider.notifier).reset();
    });
  }

  void _routeOnce(String location) {
    if (_routed || !mounted) return;
    _routed = true;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!mounted) return;
      context.go(location);
    });
  }

  @override
  Widget build(BuildContext context) {
    final pricingAsync = ref.watch(chatPricingProvider);

    return Scaffold(
      backgroundColor: HaloTokens.bg,
      body: pricingAsync.when(
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (_, __) {
          // Pricing fetch failed — fall through to method-pick (which fetches
          // pricing again and surfaces the error there).
          _routeOnce('/payment/method-pick');
          return const SizedBox.shrink();
        },
        data: (pricing) {
          if (pricing.firstSessionDiscount?.eligible ?? false) {
            _routeOnce('/payment/discount-paywall');
          } else {
            _routeOnce('/payment/method-pick');
          }
          return const SizedBox.shrink();
        },
      ),
    );
  }
}
