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 RightsCardDetailScreen extends StatefulWidget {
  final String cardId;
  const RightsCardDetailScreen({super.key, required this.cardId});

  @override
  State<RightsCardDetailScreen> createState() => _RightsCardDetailScreenState();
}

class _RightsCardDetailScreenState extends State<RightsCardDetailScreen> {
  Map<String, dynamic>? _card;
  bool _loading = true;

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

  Future<void> _load() async {
    try {
      _card = await context.read<AppProvider>().api.getRightsCardDetail(widget.cardId);
    } catch (_) {
      // Fallback to local data
      final provider = context.read<AppProvider>();
      _card = provider.rightsCards.firstWhere(
        (c) => c['id']?.toString() == widget.cardId,
        orElse: () => {},
      );
    }
    setState(() => _loading = false);
  }

  static const _categoryIcons = <String, IconData>{
    'arrest': Icons.gavel_rounded,
    'criminal': Icons.gavel_rounded,
    'civil': Icons.balance_rounded,
    'family': Icons.family_restroom_rounded,
    'employment': Icons.work_rounded,
    'fired': Icons.work_off_rounded,
    'immigration': Icons.flight_takeoff_rounded,
    'housing': Icons.home_rounded,
    'eviction': Icons.home_work_rounded,
    'consumer': Icons.shopping_cart_rounded,
    'workplace': Icons.business_center_rounded,
  };

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.navy,
      appBar: AppBar(
        title: Text('Rights Card', 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))
          : _card == null || _card!.isEmpty
              ? Center(child: Text('Card not found', style: AppTypography.bodyMd.copyWith(color: AppColors.textMuted)))
              : SingleChildScrollView(
                  padding: const EdgeInsets.fromLTRB(16, 0, 16, 40),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // Header card
                      TiltCard(
                        child: Container(
                          width: double.infinity,
                          padding: const EdgeInsets.all(24),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(20),
                            gradient: LinearGradient(
                              begin: Alignment.topLeft,
                              end: Alignment.bottomRight,
                              colors: [
                                AppColors.royalBlue.withValues(alpha: 0.3),
                                AppColors.navy,
                              ],
                            ),
                            border: Border.all(color: AppColors.glassBorderStrong),
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Icon(
                                _categoryIcons[_card!['category']?.toString().toLowerCase()] ?? Icons.shield_rounded,
                                color: AppColors.gold, size: 36,
                              ),
                              const SizedBox(height: 14),
                              Text(_card!['title']?.toString() ?? 'Right',
                                  style: AppTypography.headingLg.copyWith(color: Colors.white)),
                              const SizedBox(height: 8),
                              Row(
                                children: [
                                  if (_card!['category'] != null)
                                    Container(
                                      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                                      decoration: BoxDecoration(
                                        color: AppColors.royalBlue.withValues(alpha: 0.2),
                                        borderRadius: BorderRadius.circular(8),
                                      ),
                                      child: Text(_card!['category'].toString(),
                                          style: AppTypography.label.copyWith(color: AppColors.royalBlue)),
                                    ),
                                  const SizedBox(width: 8),
                                  if (_card!['country'] != null)
                                    Container(
                                      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                                      decoration: BoxDecoration(
                                        color: AppColors.gold.withValues(alpha: 0.12),
                                        borderRadius: BorderRadius.circular(8),
                                      ),
                                      child: Text(_card!['country'].toString(),
                                          style: AppTypography.label.copyWith(color: AppColors.gold)),
                                    ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                      const SizedBox(height: 20),

                      // Parse content - it can be a Map with summary, rights, do_not, steps
                      ..._buildContentSections(),
                    ],
                  ),
                ),
    );
  }
  
  List<Widget> _buildContentSections() {
    final List<Widget> widgets = [];
    
    // Get content - could be Map or String
    final content = _card!['content'];
    
    if (content is Map) {
      // Summary from content
      if (content['summary'] != null) {
        widgets.addAll([
          Text('Summary', style: AppTypography.headingMd.copyWith(color: AppColors.gold)),
          const SizedBox(height: 8),
          GlassCard(
            padding: const EdgeInsets.all(16),
            child: Text(content['summary'].toString(),
                style: AppTypography.bodyMd.copyWith(color: Colors.white, height: 1.6)),
          ),
          const SizedBox(height: 16),
        ]);
      }
      
      // Rights list
      if (content['rights'] != null && content['rights'] is List) {
        widgets.addAll([
          Text('Your Rights', style: AppTypography.headingMd.copyWith(color: AppColors.gold)),
          const SizedBox(height: 8),
          ...(content['rights'] as List).map((right) => Padding(
            padding: const EdgeInsets.only(bottom: 8),
            child: GlassCard(
              padding: const EdgeInsets.all(14),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    width: 24, height: 24,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: AppColors.success.withValues(alpha: 0.2),
                    ),
                    child: const Icon(Icons.check_rounded, color: AppColors.success, size: 14),
                  ),
                  const SizedBox(width: 12),
                  Expanded(child: Text(right.toString(),
                      style: AppTypography.bodyMd.copyWith(color: Colors.white, height: 1.5))),
                ],
              ),
            ),
          )),
          const SizedBox(height: 16),
        ]);
      }
      
      // Do Not list (warnings)
      if (content['do_not'] != null && content['do_not'] is List) {
        widgets.addAll([
          Text('Do NOT', style: AppTypography.headingMd.copyWith(color: AppColors.error)),
          const SizedBox(height: 8),
          ...(content['do_not'] as List).map((item) => Padding(
            padding: const EdgeInsets.only(bottom: 8),
            child: GlassCard(
              padding: const EdgeInsets.all(14),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    width: 24, height: 24,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: AppColors.error.withValues(alpha: 0.2),
                    ),
                    child: const Icon(Icons.close_rounded, color: AppColors.error, size: 14),
                  ),
                  const SizedBox(width: 12),
                  Expanded(child: Text(item.toString(),
                      style: AppTypography.bodyMd.copyWith(color: Colors.white, height: 1.5))),
                ],
              ),
            ),
          )),
          const SizedBox(height: 16),
        ]);
      }
      
      // Steps list
      if (content['steps'] != null && content['steps'] is List) {
        widgets.addAll([
          Text('Steps to Take', style: AppTypography.headingMd.copyWith(color: AppColors.gold)),
          const SizedBox(height: 8),
          ...(content['steps'] as List).asMap().entries.map((e) => Padding(
            padding: const EdgeInsets.only(bottom: 8),
            child: GlassCard(
              padding: const EdgeInsets.all(14),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    width: 28, height: 28,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: AppColors.royalBlue.withValues(alpha: 0.2),
                    ),
                    child: Center(
                      child: Text('${e.key + 1}',
                          style: AppTypography.bodySm.copyWith(color: AppColors.royalBlue, fontWeight: FontWeight.w700)),
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(child: Text(e.value.toString(),
                      style: AppTypography.bodyMd.copyWith(color: Colors.white, height: 1.5))),
                ],
              ),
            ),
          )),
        ]);
      }
    } else if (content != null) {
      // Fallback: show content as string
      widgets.addAll([
        Text('Details', style: AppTypography.headingMd.copyWith(color: AppColors.gold)),
        const SizedBox(height: 8),
        GlassCard(
          padding: const EdgeInsets.all(16),
          child: Text(content.toString(),
              style: AppTypography.bodyMd.copyWith(color: Colors.white, height: 1.6)),
        ),
        const SizedBox(height: 16),
      ]);
    }
    
    // Also check root-level summary/steps (fallback)
    if (widgets.isEmpty) {
      if (_card!['summary'] != null) {
        widgets.addAll([
          Text('Summary', style: AppTypography.headingMd.copyWith(color: AppColors.gold)),
          const SizedBox(height: 8),
          GlassCard(
            padding: const EdgeInsets.all(16),
            child: Text(_card!['summary'].toString(),
                style: AppTypography.bodyMd.copyWith(color: Colors.white, height: 1.6)),
          ),
          const SizedBox(height: 16),
        ]);
      }
      
      if (_card!['steps'] != null && _card!['steps'] is List) {
        widgets.addAll([
          Text('Steps to Take', style: AppTypography.headingMd.copyWith(color: AppColors.gold)),
          const SizedBox(height: 8),
          ...(_card!['steps'] as List).asMap().entries.map((e) => Padding(
            padding: const EdgeInsets.only(bottom: 8),
            child: GlassCard(
              padding: const EdgeInsets.all(14),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    width: 28, height: 28,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: AppColors.royalBlue.withValues(alpha: 0.2),
                    ),
                    child: Center(
                      child: Text('${e.key + 1}',
                          style: AppTypography.bodySm.copyWith(color: AppColors.royalBlue, fontWeight: FontWeight.w700)),
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(child: Text(e.value.toString(),
                      style: AppTypography.bodyMd.copyWith(color: Colors.white, height: 1.5))),
                ],
              ),
            ),
          )),
        ]);
      }
    }
    
    // Citations
    if (_card!['citations'] != null && _card!['citations'] is List) {
      widgets.addAll([
        const SizedBox(height: 8),
        Text('Legal Citations', style: AppTypography.headingMd.copyWith(color: AppColors.textMuted)),
        const SizedBox(height: 8),
        GlassCard(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: (_card!['citations'] as List).map((c) => Padding(
              padding: const EdgeInsets.only(bottom: 6),
              child: Text('• $c',
                  style: AppTypography.bodySm.copyWith(color: AppColors.textSecondary, height: 1.4)),
            )).toList(),
          ),
        ),
      ]);
    }
    
    return widgets;
  }
}
