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 RightsCardsScreen extends StatefulWidget {
  const RightsCardsScreen({super.key});

  @override
  State<RightsCardsScreen> createState() => _RightsCardsScreenState();
}

class _RightsCardsScreenState extends State<RightsCardsScreen> {
  String _selectedCategory = 'All';
  String? _selectedCountry;

  // Backend categories from RightsCard model
  static const _categories = [
    'All',
    'arrest',
    'traffic',
    'eviction',
    'fired',
    'divorce',
    'harassment',
    'police',
    'landlord',
    'immigration',
    'consumer',
    'workplace',
  ];

  static const _categoryLabels = <String, String>{
    'All': 'All Rights',
    'arrest': 'Arrested',
    'traffic': 'Traffic Stop',
    'eviction': 'Eviction',
    'fired': 'Fired/Terminated',
    'divorce': 'Divorce',
    'harassment': 'Harassment',
    'police': 'Police Encounter',
    'landlord': 'Landlord Dispute',
    'immigration': 'Immigration',
    'consumer': 'Consumer Rights',
    'workplace': 'Workplace Rights',
  };

  static const _categoryIcons = <String, IconData>{
    'All': Icons.apps_rounded,
    'arrest': Icons.gavel_rounded,
    'traffic': Icons.directions_car_rounded,
    'eviction': Icons.home_work_rounded,
    'fired': Icons.work_off_rounded,
    'divorce': Icons.family_restroom_rounded,
    'harassment': Icons.warning_rounded,
    'police': Icons.local_police_rounded,
    'landlord': Icons.apartment_rounded,
    'immigration': Icons.flight_takeoff_rounded,
    'consumer': Icons.shopping_cart_rounded,
    'workplace': Icons.business_center_rounded,
  };

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final provider = context.read<AppProvider>();
      final userCountry = provider.profile?['country']?.toString();
      if (userCountry != null && userCountry.isNotEmpty) {
        setState(() => _selectedCountry = userCountry);
      }
      if (provider.rightsCards.isEmpty) {
        provider.loadRightsCards();
      }
    });
  }

  List<Map<String, dynamic>> get _filteredCards {
    final provider = context.read<AppProvider>();
    var cards = provider.rightsCards;

    if (_selectedCountry != null && _selectedCountry!.isNotEmpty) {
      cards = cards.where((c) {
        final cardCountry = c['country']?.toString().toUpperCase() ?? '';
        return cardCountry == _selectedCountry!.toUpperCase() || cardCountry.isEmpty;
      }).toList();
    }

    if (_selectedCategory != 'All') {
      cards = cards.where((c) {
        final cat = c['category']?.toString().toLowerCase() ?? '';
        return cat == _selectedCategory.toLowerCase();
      }).toList();
    }

    return cards;
  }

  List<String> get _availableCountries {
    final provider = context.read<AppProvider>();
    final countries = provider.rightsCards
        .map((c) => c['country']?.toString().toUpperCase() ?? '')
        .where((c) => c.isNotEmpty)
        .toSet()
        .toList()
      ..sort();
    return ['All', ...countries];
  }

  void _showCountryPicker() {
    showModalBottomSheet(
      context: context,
      backgroundColor: AppColors.navy,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (ctx) => SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(20),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Select Country', style: AppTypography.headingMd.copyWith(color: Colors.white)),
              const SizedBox(height: 16),
              Wrap(
                spacing: 8,
                runSpacing: 8,
                children: _availableCountries.map((country) {
                  final isSelected = country == 'All'
                      ? _selectedCountry == null
                      : country == _selectedCountry;
                  return GestureDetector(
                    onTap: () {
                      setState(() => _selectedCountry = country == 'All' ? null : country);
                      Navigator.pop(ctx);
                    },
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                      decoration: BoxDecoration(
                        color: isSelected ? AppColors.royalBlue : AppColors.glassSurface,
                        borderRadius: BorderRadius.circular(10),
                        border: Border.all(
                          color: isSelected ? AppColors.royalBlue : AppColors.glassBorder,
                        ),
                      ),
                      child: Text(
                        country == 'All' ? 'All Countries' : country,
                        style: AppTypography.bodySm.copyWith(
                          color: isSelected ? Colors.white : AppColors.textSecondary,
                          fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                        ),
                      ),
                    ),
                  );
                }).toList(),
              ),
              const SizedBox(height: 20),
            ],
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    context.watch<AppProvider>();
    final cards = _filteredCards;
    final provider = context.read<AppProvider>();

    return Scaffold(
      backgroundColor: Colors.transparent,
      appBar: AppBar(
        title: Text('Your Rights', style: AppTypography.headingLg.copyWith(color: Colors.white)),
        backgroundColor: Colors.transparent,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
        actions: [
          Padding(
            padding: const EdgeInsets.only(right: 8),
            child: GestureDetector(
              onTap: _showCountryPicker,
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(
                  color: AppColors.glassSurface,
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: AppColors.glassBorder),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const Icon(Icons.public_rounded, size: 16, color: AppColors.textSecondary),
                    const SizedBox(width: 6),
                    Text(_selectedCountry ?? 'All', style: AppTypography.bodySm.copyWith(color: Colors.white)),
                    const SizedBox(width: 4),
                    const Icon(Icons.arrow_drop_down, size: 18, color: AppColors.textMuted),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
      body: provider.rightsLoading
          ? const Center(child: CircularProgressIndicator(color: AppColors.royalBlue))
          : Column(
              children: [
                SizedBox(
                  height: 44,
                  child: ListView.builder(
                    scrollDirection: Axis.horizontal,
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    itemCount: _categories.length,
                    itemBuilder: (context, i) {
                      final cat = _categories[i];
                      final selected = cat == _selectedCategory;
                      return Padding(
                        padding: const EdgeInsets.only(right: 8),
                        child: GestureDetector(
                          onTap: () => setState(() => _selectedCategory = cat),
                          child: AnimatedContainer(
                            duration: const Duration(milliseconds: 250),
                            curve: Curves.easeOut,
                            padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
                            decoration: BoxDecoration(
                              color: selected ? AppColors.royalBlue.withValues(alpha: 0.25) : AppColors.glassSurface,
                              borderRadius: BorderRadius.circular(22),
                              border: Border.all(
                                color: selected ? AppColors.royalBlue : AppColors.glassBorder,
                                width: selected ? 1.5 : 1,
                              ),
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Icon(_categoryIcons[cat] ?? Icons.category_rounded, size: 16,
                                    color: selected ? AppColors.royalBlue : AppColors.textSecondary),
                                const SizedBox(width: 6),
                                Text(_categoryLabels[cat] ?? cat, style: AppTypography.bodySm.copyWith(
                                  color: selected ? Colors.white : AppColors.textSecondary,
                                  fontWeight: selected ? FontWeight.w600 : FontWeight.normal,
                                )),
                              ],
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ),
                const SizedBox(height: 16),

                Expanded(
                  child: cards.isEmpty
                      ? Center(
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Icon(Icons.shield_outlined, size: 48, color: AppColors.glassBorder),
                              const SizedBox(height: 12),
                              Text('No rights cards found', style: AppTypography.bodyMd.copyWith(color: AppColors.textMuted)),
                              const SizedBox(height: 4),
                              Text(
                                _selectedCountry != null ? 'Try selecting a different country' : 'Try changing the category filter',
                                style: AppTypography.bodySm.copyWith(color: AppColors.textMuted),
                              ),
                            ],
                          ),
                        )
                      : GridView.builder(
                          padding: const EdgeInsets.fromLTRB(16, 0, 16, 100),
                          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 2, crossAxisSpacing: 12, mainAxisSpacing: 12, childAspectRatio: 0.75,
                          ),
                          itemCount: cards.length,
                          itemBuilder: (context, i) {
                            final card = cards[i];
                            final category = card['category']?.toString().toLowerCase() ?? '';
                            final country = card['country']?.toString().toUpperCase() ?? '';

                            return GestureDetector(
                              onTap: () {
                                final cardId = card['id']?.toString();
                                if (cardId != null) {
                                  Navigator.of(context).pushNamed('/rights-detail', arguments: {'cardId': cardId});
                                }
                              },
                              child: TiltCard(
                                child: Container(
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(16),
                                    gradient: LinearGradient(
                                      begin: Alignment.topLeft, end: Alignment.bottomRight,
                                      colors: [AppColors.glassSurface, AppColors.glassSurface.withValues(alpha: 0.5)],
                                    ),
                                    border: Border.all(color: AppColors.glassBorder),
                                  ),
                                  padding: const EdgeInsets.all(14),
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Row(
                                        children: [
                                          Container(
                                            width: 38, height: 38,
                                            decoration: BoxDecoration(gradient: AppColors.blueGradient, borderRadius: BorderRadius.circular(10)),
                                            child: Icon(_categoryIcons[category] ?? Icons.shield_rounded, color: Colors.white, size: 18),
                                          ),
                                          const Spacer(),
                                          if (country.isNotEmpty)
                                            Container(
                                              padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                                              decoration: BoxDecoration(
                                                color: AppColors.gold.withValues(alpha: 0.15),
                                                borderRadius: BorderRadius.circular(4),
                                              ),
                                              child: Text(country, style: AppTypography.label.copyWith(color: AppColors.gold, fontSize: 10)),
                                            ),
                                        ],
                                      ),
                                      const SizedBox(height: 12),
                                      Text(card['title']?.toString() ?? 'Right',
                                          style: AppTypography.headingMd.copyWith(color: Colors.white, fontSize: 14, height: 1.2),
                                          maxLines: 2, overflow: TextOverflow.ellipsis),
                                      const SizedBox(height: 6),
                                      Expanded(
                                        child: Text(_getCardSummary(card),
                                            style: AppTypography.bodySm.copyWith(color: AppColors.textSecondary, height: 1.3, fontSize: 12),
                                            maxLines: 4, overflow: TextOverflow.ellipsis),
                                      ),
                                      const SizedBox(height: 8),
                                      Container(
                                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                                        decoration: BoxDecoration(
                                          color: AppColors.royalBlue.withValues(alpha: 0.12),
                                          borderRadius: BorderRadius.circular(6),
                                        ),
                                        child: Text(_categoryLabels[category] ?? category,
                                            style: AppTypography.label.copyWith(color: AppColors.royalBlue, fontSize: 10)),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            );
                          },
                        ),
                ),
              ],
            ),
    );
  }

  String _getCardSummary(Map<String, dynamic> card) {
    final content = card['content'];
    if (content is Map) {
      final summary = content['summary'] ?? content['description'] ?? content['intro'];
      if (summary != null) return summary.toString();
      final bullets = content['bullets'] ?? content['points'] ?? content['rights'];
      if (bullets is List && bullets.isNotEmpty) {
        return bullets.first.toString();
      }
    }
    return card['summary']?.toString() ?? '';
  }
}
