import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_typography.dart';
import '../../services/app_provider.dart';
import '../../widgets/glass_card.dart';
import '../../widgets/tilt_card.dart';

class StatsScreen extends StatefulWidget {
  const StatsScreen({super.key});

  @override
  State<StatsScreen> createState() => _StatsScreenState();
}

class _StatsScreenState extends State<StatsScreen> {
  Map<String, dynamic>? _stats;
  Map<String, dynamic>? _subscription;
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _load();
  }

  Future<void> _load() async {
    final api = context.read<AppProvider>().api;
    try {
      final results = await Future.wait([
        api.getStats(),
        api.getSubscriptionStatus(),
      ]);
      _stats = results[0];
      _subscription = results[1];
    } catch (_) {}
    setState(() => _loading = false);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.navy,
      appBar: AppBar(
        title: Text('Usage & Plan', style: AppTypography.headingLg.copyWith(color: Colors.white)),
        backgroundColor: Colors.transparent,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: _loading
          ? const Center(child: CircularProgressIndicator(color: AppColors.royalBlue))
          : SingleChildScrollView(
              padding: const EdgeInsets.fromLTRB(16, 0, 16, 40),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Plan card
                  if (_subscription != null)
                    TiltCard(
                      child: Container(
                        width: double.infinity,
                        padding: const EdgeInsets.all(24),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(20),
                          gradient: AppColors.heroGradient,
                          border: Border.all(color: AppColors.glassBorderStrong),
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text('Current Plan', style: AppTypography.bodySm.copyWith(color: AppColors.textMuted)),
                            const SizedBox(height: 4),
                            Text(
                              (_subscription!['plan']?.toString() ?? 'Free').toUpperCase(),
                              style: AppTypography.displayLg.copyWith(color: AppColors.gold),
                            ),
                          ],
                        ),
                      ),
                    ),
                  const SizedBox(height: 24),

                  // Usage Stats
                  if (_stats != null) ...[
                    Text('Usage', style: AppTypography.headingMd.copyWith(color: Colors.white)),
                    const SizedBox(height: 12),
                    _statTile(Icons.chat_rounded, 'Total Queries',
                        _stats!['total_queries']?.toString() ?? '0'),
                    _statTile(Icons.today_rounded, 'Today\'s Queries',
                        '${_stats!['daily_queries_used'] ?? 0} / ${_stats!['daily_queries_limit'] ?? 0}'),
                    _statTile(Icons.description_rounded, 'Documents',
                        '${_stats!['daily_docs_used'] ?? 0} / ${_stats!['daily_docs_limit'] ?? 0} today (${_stats!['total_documents'] ?? 0} total)'),
                    _statTile(Icons.mic_rounded, 'Voice Sessions',
                        _stats!['total_voice_sessions']?.toString() ?? '0'),
                    _statTile(Icons.public_rounded, 'Countries Queried',
                        _stats!['countries_queried']?.toString() ?? '0'),
                    _statTile(Icons.topic_rounded, 'Topics Queried',
                        _stats!['topics_queried']?.toString() ?? '0'),
                    if (_stats!['last_active_date'] != null)
                      _statTile(Icons.schedule_rounded, 'Last Active',
                          _stats!['last_active_date'].toString()),
                  ],
                  
                  const SizedBox(height: 24),
                  
                  // Available Plans
                  Text('Available Plans', style: AppTypography.headingMd.copyWith(color: Colors.white)),
                  const SizedBox(height: 12),
                  
                  _planCard(
                    name: 'FREE',
                    price: '\$0',
                    period: 'forever',
                    features: [
                      '10 queries per day',
                      '2 document scans per day',
                      '5 countries',
                      '3 voice sessions per day',
                      'Basic legal information',
                    ],
                    isCurrent: (_subscription?['plan']?.toString().toLowerCase() ?? 'free') == 'free',
                  ),
                  const SizedBox(height: 12),
                  
                  _planCard(
                    name: 'PRO',
                    price: '\$9.99',
                    period: 'per month',
                    features: [
                      '100 queries per day',
                      '25 document scans per day',
                      '30 countries',
                      '15 voice sessions per day',
                      'Priority support',
                      'Contract drafting',
                      'Cost estimations',
                    ],
                    isCurrent: (_subscription?['plan']?.toString().toLowerCase() ?? '') == 'pro',
                    highlight: true,
                  ),
                  const SizedBox(height: 12),
                  
                  _planCard(
                    name: 'BUSINESS',
                    price: '\$29.99',
                    period: 'per month',
                    features: [
                      'Unlimited queries',
                      'Unlimited document scans',
                      'All 155+ countries',
                      'Unlimited voice sessions',
                      '24/7 priority support',
                      'All premium features',
                      'API access',
                      'Team management',
                    ],
                    isCurrent: (_subscription?['plan']?.toString().toLowerCase() ?? '') == 'business',
                  ),
                ],
              ),
            ),
    );
  }
  
  Widget _planCard({
    required String name,
    required String price,
    required String period,
    required List<String> features,
    bool isCurrent = false,
    bool highlight = false,
  }) {
    return GlassCard(
      highlighted: highlight,
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(name, style: AppTypography.headingMd.copyWith(
                color: highlight ? AppColors.gold : Colors.white,
              )),
              if (isCurrent)
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                  decoration: BoxDecoration(
                    color: AppColors.success.withValues(alpha: 0.2),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Text('CURRENT', style: AppTypography.label.copyWith(color: AppColors.success)),
                ),
            ],
          ),
          const SizedBox(height: 8),
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text(price, style: AppTypography.headingLg.copyWith(color: Colors.white)),
              const SizedBox(width: 4),
              Padding(
                padding: const EdgeInsets.only(bottom: 4),
                child: Text(period, style: AppTypography.bodySm.copyWith(color: AppColors.textMuted)),
              ),
            ],
          ),
          const SizedBox(height: 16),
          ...features.map((f) => Padding(
            padding: const EdgeInsets.only(bottom: 8),
            child: Row(
              children: [
                Icon(Icons.check_circle_rounded, size: 16, color: AppColors.success),
                const SizedBox(width: 10),
                Expanded(child: Text(f, style: AppTypography.bodyMd.copyWith(color: AppColors.textSecondary))),
              ],
            ),
          )),
          if (!isCurrent) ...[
            const SizedBox(height: 12),
            GestureDetector(
              onTap: () {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(
                    content: const Text('Subscription coming soon!'),
                    backgroundColor: AppColors.royalBlue,
                    behavior: SnackBarBehavior.floating,
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                  ),
                );
              },
              child: Container(
                width: double.infinity,
                height: 44,
                decoration: BoxDecoration(
                  gradient: highlight ? AppColors.goldGradient : AppColors.blueGradient,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Center(
                  child: Text('Upgrade', style: AppTypography.button.copyWith(
                    color: highlight ? AppColors.navy : Colors.white,
                  )),
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _statTile(IconData icon, String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 10),
      child: GlassCard(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
        child: Row(
          children: [
            Container(
              width: 36, height: 36,
              decoration: BoxDecoration(
                color: AppColors.royalBlue.withValues(alpha: 0.12),
                borderRadius: BorderRadius.circular(10),
              ),
              child: Icon(icon, color: AppColors.royalBlue, size: 18),
            ),
            const SizedBox(width: 14),
            Expanded(child: Text(label, style: AppTypography.bodyMd.copyWith(color: AppColors.textSecondary))),
            Text(value, style: AppTypography.bodyMd.copyWith(color: Colors.white, fontWeight: FontWeight.w600)),
          ],
        ),
      ),
    );
  }
}
