import 'dart:html' as html;
import 'package:flutter/material.dart';
import 'package:manager_api_new/api.dart';
import 'package:manager_app/Components/common_loader.dart';
import 'package:manager_app/Components/message_notification.dart';
import 'package:manager_app/Components/rounded_button.dart';
import 'package:manager_app/Models/managerContext.dart';
import 'package:manager_app/app_context.dart';
import 'package:manager_app/constants.dart';
import 'package:manager_app/l10n/app_localizations.dart';
import 'package:provider/provider.dart';
/// Subscription screen for the Essentiel plan only — Pro/Premium/Enterprise
/// remain fully manual (contact commercial), so they have no self-service
/// screen here. Shows trial status + what's included, and lets the user
/// convert to a paid subscription via a Stripe-hosted Checkout Session.
///
/// The "Add-ons" section below is intentionally a placeholder for now — it's
/// the future home of the paid AI request quota add-on, not implemented yet.
class SubscriptionScreen extends StatefulWidget {
const SubscriptionScreen({Key? key}) : super(key: key);
@override
_SubscriptionScreenState createState() => _SubscriptionScreenState();
}
class _SubscriptionScreenState extends State {
bool isRedirecting = false;
static const _includedFeatures = [
"App visiteur web, ouverte par QR code — aucune installation",
"Contenus, agenda, plans et sections illimités",
"Multilingue — vos visiteurs choisissent leur langue",
"Vos couleurs et votre logo, votre adresse dédiée",
];
Future _startCheckout(ManagerAppContext ctx) async {
setState(() => isRedirecting = true);
try {
final url = await ctx.clientAPI!.onboardingApi!.onboardingCreateCheckoutSession();
html.window.open(url, '_blank');
} catch (e) {
showNotification(kError, kWhite, AppLocalizations.of(context)!.subscriptionCheckoutError, context, null);
} finally {
if (mounted) setState(() => isRedirecting = false);
}
}
/// Portail Stripe : changer de carte, relire ses factures, résilier. Stripe héberge la page.
///
/// ⚠️ Le 409 n'est pas une erreur à afficher comme telle : il dit que l'instance n'a pas de
/// client Stripe — le cas de **tous les clients venus de la migration Mongo**, qui n'ont
/// jamais souscrit en ligne. Leur montrer « réessayez plus tard » les ferait attendre
/// quelque chose qui n'arrivera pas ; le message dit que leur facturation passe par nous.
Future _openBillingPortal(ManagerAppContext ctx) async {
setState(() => isRedirecting = true);
try {
final url = await ctx.clientAPI!.onboardingApi!.onboardingCreateBillingPortalSession();
html.window.open(url, '_blank');
} on ApiException catch (e) {
if (!mounted) return;
final l = AppLocalizations.of(context)!;
final message = e.code == 409 ? l.subscriptionPortalNoCustomer : l.subscriptionPortalError;
showNotification(kError, kWhite, message, context, null);
} catch (e) {
if (mounted) {
showNotification(kError, kWhite, AppLocalizations.of(context)!.subscriptionPortalError, context, null);
}
} finally {
if (mounted) setState(() => isRedirecting = false);
}
}
String _formatDate(DateTime date) {
final d = date.toLocal();
return "${d.day.toString().padLeft(2, '0')}/${d.month.toString().padLeft(2, '0')}/${d.year}";
}
@override
Widget build(BuildContext context) {
final l = AppLocalizations.of(context)!;
final managerCtx = Provider.of(context).getContext() as ManagerAppContext;
final instance = managerCtx.instanceDTO;
final isTrialActive = instance?.isTrialActive == true;
final trialEndsAt = instance?.trialEndsAt;
return SingleChildScrollView(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(l.subscriptionTitle, style: TextStyle(fontSize: 24, fontWeight: FontWeight.w600, color: kPrimaryColor)),
const SizedBox(height: 16),
Card(
elevation: 0,
color: isTrialActive ? kPrimaryColor.withValues(alpha: 0.06) : kSuccess.withValues(alpha: 0.08),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: BorderSide(color: (isTrialActive ? kPrimaryColor : kSuccess).withValues(alpha: 0.25)),
),
child: Padding(
padding: const EdgeInsets.all(20),
child: Row(
children: [
Icon(
isTrialActive ? Icons.hourglass_top_rounded : Icons.check_circle_outline,
color: isTrialActive ? kPrimaryColor : kSuccess,
size: 32,
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
isTrialActive ? l.subscriptionTrialActive : l.subscriptionPlanActive,
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
),
const SizedBox(height: 4),
Text(
isTrialActive
? (trialEndsAt != null
? l.subscriptionTrialEndsAt(_formatDate(trialEndsAt))
: l.subscriptionTrialNoDate)
: l.subscriptionPlanActiveDesc,
style: TextStyle(fontSize: 13, color: Colors.grey[700]),
),
],
),
),
],
),
),
),
const SizedBox(height: 24),
Text(l.subscriptionIncludedTitle, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
const SizedBox(height: 12),
..._includedFeatures.map((feature) => Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(Icons.check, color: kSuccess, size: 18),
const SizedBox(width: 8),
Expanded(child: Text(feature, style: const TextStyle(fontSize: 14))),
],
),
)),
const SizedBox(height: 16),
if (isRedirecting)
const CommonLoader(iconSize: 32)
else if (isTrialActive)
RoundedButton(
text: l.subscriptionUpgradeBtn,
fontSize: 15,
vertical: 14,
horizontal: 24,
press: () => _startCheckout(managerCtx),
)
else ...[
// Hors essai, l'abonnement est en cours : ce qu'on peut encore vouloir faire ici,
// c'est corriger une carte ou relire une facture — pas souscrire une seconde fois.
Text(l.subscriptionManageDesc, style: TextStyle(fontSize: 13, color: Colors.grey[700])),
const SizedBox(height: 12),
RoundedButton(
text: l.subscriptionManageBtn,
fontSize: 15,
vertical: 14,
horizontal: 24,
press: () => _openBillingPortal(managerCtx),
),
],
const SizedBox(height: 32),
Text(l.subscriptionAddonsTitle, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
const SizedBox(height: 8),
Text(
l.subscriptionAddonsComingSoon,
style: TextStyle(fontSize: 13, color: Colors.grey[600]),
),
],
),
);
}
}