import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:it0_app/l10n/app_localizations.dart';
import '../../../../core/theme/app_colors.dart';
import '../providers/billing_provider.dart';

class BillingOverviewPage extends ConsumerWidget {
  const BillingOverviewPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final billingAsync = ref.watch(billingOverviewProvider);
    final theme = Theme.of(context);
    final isDark = theme.brightness == Brightness.dark;
    final cardColor = isDark ? AppColors.surface : Colors.white;

    return Scaffold(
      appBar: AppBar(title: Text(AppLocalizations.of(context).billingTitle)),
      body: billingAsync.when(
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (e, _) => Center(child: Text('加载失败: $e')),
        data: (billing) => ListView(
          padding: const EdgeInsets.all(16),
          children: [
            // Subscription Card
            _SubscriptionCard(
              planName: billing.planDisplayName,
              status: billing.subscriptionStatus,
              periodEnd: billing.currentPeriodEnd,
              cardColor: cardColor,
              theme: theme,
            ),
            const SizedBox(height: 16),

            // Token Usage Card
            _UsageCard(
              usedTokens: billing.usedTokens,
              limitTokens: billing.limitTokens,
              cardColor: cardColor,
              theme: theme,
            ),
            const SizedBox(height: 16),

            // Recent Invoice Card
            if (billing.latestInvoice != null)
              _InvoiceCard(
                invoice: billing.latestInvoice!,
                cardColor: cardColor,
                theme: theme,
              ),
            const SizedBox(height: 24),

            // Upgrade Button
            if (billing.subscriptionStatus != 'enterprise')
              ElevatedButton.icon(
                onPressed: () {
                  // Open web admin billing/plans in browser
                  // or show a dialog for now
                  _showUpgradeDialog(context);
                },
                icon: const Icon(Icons.upgrade),
                label: Text(AppLocalizations.of(context).upgradeButton),
                style: ElevatedButton.styleFrom(
                  minimumSize: const Size(double.infinity, 48),
                  backgroundColor: AppColors.primary,
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  void _showUpgradeDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: Text(AppLocalizations.of(ctx).upgradeDialogTitle),
        content: Text(AppLocalizations.of(ctx).upgradeDialogMessage),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(),
            child: Text(AppLocalizations.of(ctx).acknowledgeButton),
          ),
        ],
      ),
    );
  }
}

class _SubscriptionCard extends StatelessWidget {
  final String planName;
  final String status;
  final DateTime? periodEnd;
  final Color cardColor;
  final ThemeData theme;

  const _SubscriptionCard({
    required this.planName,
    required this.status,
    required this.periodEnd,
    required this.cardColor,
    required this.theme,
  });

  Color _statusColor(String status) => switch (status) {
        'active' => Colors.green,
        'trialing' => Colors.blue,
        'past_due' => Colors.orange,
        _ => Colors.grey,
      };

  String _statusLabel(String status, BuildContext context) {
    final l = AppLocalizations.of(context);
    return switch (status) {
      'active' => l.billingStatusActive,
      'trialing' => l.billingStatusTrialing,
      'past_due' => l.billingStatusPastDue,
      'cancelled' => l.billingStatusCancelled,
      'expired' => l.billingStatusExpired,
      _ => status,
    };
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      color: cardColor,
      elevation: 0,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
        side: BorderSide(color: Colors.grey.withOpacity(0.15)),
      ),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                const Icon(Icons.credit_card, size: 20, color: AppColors.primary),
                const SizedBox(width: 8),
                Text(AppLocalizations.of(context).currentPlanLabel, style: theme.textTheme.bodySmall?.copyWith(color: Colors.grey)),
              ],
            ),
            const SizedBox(height: 12),
            Row(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Text(
                  planName,
                  style: theme.textTheme.headlineMedium?.copyWith(fontWeight: FontWeight.bold),
                ),
                const SizedBox(width: 10),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
                  decoration: BoxDecoration(
                    color: _statusColor(status).withOpacity(0.1),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Text(
                    _statusLabel(status, context),
                    style: TextStyle(fontSize: 12, color: _statusColor(status), fontWeight: FontWeight.w600),
                  ),
                ),
              ],
            ),
            if (periodEnd != null) ...[
              const SizedBox(height: 6),
              Text(
                '${AppLocalizations.of(context).periodEndLabel}${_formatDate(periodEnd!)}',
                style: theme.textTheme.bodySmall?.copyWith(color: Colors.grey),
              ),
            ],
          ],
        ),
      ),
    );
  }

  String _formatDate(DateTime d) => '${d.year}-${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')}';
}

class _UsageCard extends StatelessWidget {
  final int usedTokens;
  final int limitTokens;
  final Color cardColor;
  final ThemeData theme;

  const _UsageCard({
    required this.usedTokens,
    required this.limitTokens,
    required this.cardColor,
    required this.theme,
  });

  String _formatTokens(int n) {
    if (n >= 1000000) return '${(n / 1000000).toStringAsFixed(2)}M';
    if (n >= 1000) return '${(n / 1000).toStringAsFixed(0)}K';
    return '$n';
  }

  @override
  Widget build(BuildContext context) {
    final isUnlimited = limitTokens == -1;
    final pct = isUnlimited ? 0.0 : (usedTokens / limitTokens).clamp(0.0, 1.0);
    final barColor = pct >= 0.9 ? Colors.red : pct >= 0.7 ? Colors.orange : Colors.green;

    return Card(
      color: cardColor,
      elevation: 0,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
        side: BorderSide(color: Colors.grey.withOpacity(0.15)),
      ),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                const Icon(Icons.bolt, size: 20, color: AppColors.primary),
                const SizedBox(width: 8),
                Text(AppLocalizations.of(context).tokenUsageLabel, style: theme.textTheme.bodySmall?.copyWith(color: Colors.grey)),
              ],
            ),
            const SizedBox(height: 16),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  _formatTokens(usedTokens),
                  style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
                ),
                Text(
                  isUnlimited ? AppLocalizations.of(context).unlimitedLabel : _formatTokens(limitTokens),
                  style: theme.textTheme.bodyMedium?.copyWith(color: Colors.grey),
                ),
              ],
            ),
            if (!isUnlimited) ...[
              const SizedBox(height: 10),
              ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: LinearProgressIndicator(
                  value: pct,
                  minHeight: 6,
                  backgroundColor: Colors.grey.withOpacity(0.2),
                  valueColor: AlwaysStoppedAnimation(barColor),
                ),
              ),
              const SizedBox(height: 6),
              Text(
                '${(pct * 100).toStringAsFixed(1)}%',
                style: theme.textTheme.bodySmall?.copyWith(color: Colors.grey),
              ),
            ],
          ],
        ),
      ),
    );
  }
}

class _InvoiceCard extends StatelessWidget {
  final LatestInvoice invoice;
  final Color cardColor;
  final ThemeData theme;

  const _InvoiceCard({
    required this.invoice,
    required this.cardColor,
    required this.theme,
  });

  @override
  Widget build(BuildContext context) {
    return Card(
      color: cardColor,
      elevation: 0,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
        side: BorderSide(color: Colors.grey.withOpacity(0.15)),
      ),
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
        leading: const Icon(Icons.receipt_long, color: AppColors.primary),
        title: Text(invoice.invoiceNumber, style: const TextStyle(fontWeight: FontWeight.w600)),
        subtitle: Text('${invoice.currency} ${invoice.amount.toStringAsFixed(2)}', style: const TextStyle(fontSize: 13)),
        trailing: Container(
          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          decoration: BoxDecoration(
            color: invoice.status == 'paid'
                ? Colors.green.withOpacity(0.1)
                : Colors.orange.withOpacity(0.1),
            borderRadius: BorderRadius.circular(20),
          ),
          child: Text(
            invoice.status == 'paid' ? AppLocalizations.of(context).invoicePaidStatus : AppLocalizations.of(context).invoiceUnpaidStatus,
            style: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w600,
              color: invoice.status == 'paid' ? Colors.green : Colors.orange,
            ),
          ),
        ),
      ),
    );
  }
}
