import 'package:flutter/material.dart';
import '../core/models.dart';
import '../l10n/l10n.dart';
import '../services/stripe_service.dart';
import 'theme.dart';
class ReportScreen extends StatefulWidget {
  final JudgmentReport report;
  const ReportScreen({super.key, required this.report});

  @override
  State<ReportScreen> createState() => _ReportScreenState();
}

class _ReportScreenState extends State<ReportScreen> {
  bool unlocked = AuthorAccess.isUnlocked;
  bool paying = false;

  @override
  void initState() {
    super.initState();
    if (AuthorAccess.isUnlocked) unlocked = true;
  }

  Future<void> _pay() async {
    setState(() => paying = true);
    final result = await StripeService.purchaseReport(
      productId: 'key_resonance_report',
      amountUsd: 9.99,
    );
    if (!mounted) return;
    setState(() {
      paying = false;
      unlocked = result.status == PaymentStatus.succeeded;
    });
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(result.message)),
    );
  }

  @override
  Widget build(BuildContext context) {
    final l = LangScope.of(context).l10n;
    final chart = widget.report.chart;
    final preview = widget.report.rawText.split('\n').take(28).join('\n');

    return Scaffold(
      appBar: AppBar(title: Text(l('report'))),
      body: ListView(
        padding: const EdgeInsets.all(20),
        children: [
          _PillarsHeader(chart: chart),
          const SizedBox(height: 16),
          Text(
            l('accuracy'),
            style: const TextStyle(color: AppTheme.jade, fontSize: 13),
          ),
          const SizedBox(height: 16),
          if (!unlocked) ...[
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [
                    AppTheme.jadeDeep.withValues(alpha: 0.08),
                    AppTheme.accent.withValues(alpha: 0.06),
                  ],
                ),
                border: Border.all(color: AppTheme.mist),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(preview, style: const TextStyle(fontFamily: 'monospace', fontSize: 12, height: 1.45)),
                  const SizedBox(height: 12),
                  Text('…', style: TextStyle(color: AppTheme.ink.withValues(alpha: 0.4))),
                ],
              ),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: paying ? null : _pay,
              child: paying
                  ? const SizedBox(
                      width: 18,
                      height: 18,
                      child: CircularProgressIndicator(strokeWidth: 2),
                    )
                  : Text(l('unlock')),
            ),
          ] else
            SelectableText(
              widget.report.rawText,
              style: const TextStyle(fontFamily: 'monospace', fontSize: 12, height: 1.45),
            ),
          const SizedBox(height: 24),
          Text(
            l('copyright'),
            style: TextStyle(fontSize: 11, color: AppTheme.ink.withValues(alpha: 0.45)),
          ),
        ],
      ),
    );
  }
}

class _PillarsHeader extends StatelessWidget {
  final BaziChart chart;
  const _PillarsHeader({required this.chart});

  @override
  Widget build(BuildContext context) {
    final pillars = chart.pillars;
    return Row(
      children: pillars.map((p) {
        return Expanded(
          child: TweenAnimationBuilder<double>(
            tween: Tween(begin: 0, end: 1),
            duration: Duration(milliseconds: 400 + pillars.indexOf(p) * 120),
            curve: Curves.easeOutCubic,
            builder: (context, v, child) => Opacity(
              opacity: v,
              child: Transform.translate(
                offset: Offset(0, 12 * (1 - v)),
                child: child,
              ),
            ),
            child: Column(
              children: [
                Text(p.label, style: TextStyle(fontSize: 11, color: AppTheme.ink.withValues(alpha: 0.5))),
                const SizedBox(height: 4),
                Text(p.stem, style: const TextStyle(fontSize: 28, fontWeight: FontWeight.w600, color: AppTheme.jadeDeep)),
                Text(p.branch, style: const TextStyle(fontSize: 28, fontWeight: FontWeight.w600, color: AppTheme.accent)),
              ],
            ),
          ),
        );
      }).toList(),
    );
  }
}
