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 '../../services/api_service.dart';
import '../../widgets/glass_card.dart';

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

  @override
  State<EmergencyScreen> createState() => _EmergencyScreenState();
}

class _EmergencyScreenState extends State<EmergencyScreen> {
  Map<String, dynamic>? _info;
  bool _loading = true;
  String? _error;

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

  Future<void> _load() async {
    setState(() { _loading = true; _error = null; });
    try {
      final country = context.read<AppProvider>().auth.userCountry;
      _info = await context.read<AppProvider>().api.getEmergencyInfo(country: country);
    } on ApiException catch (e) {
      _error = e.message;
    } catch (_) {
      _error = 'Failed to load emergency info';
    }
    setState(() => _loading = false);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.navy,
      appBar: AppBar(
        title: Text('Emergency Info', 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))
          : _error != null
              ? Center(child: Text(_error!, style: AppTypography.bodyMd.copyWith(color: AppColors.error)))
              : SingleChildScrollView(
                  padding: const EdgeInsets.fromLTRB(16, 0, 16, 40),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // Country header
                      GlassCard(
                        highlighted: true,
                        padding: const EdgeInsets.all(20),
                        child: Row(
                          children: [
                            Container(
                              width: 48,
                              height: 48,
                              decoration: BoxDecoration(
                                color: AppColors.error.withValues(alpha: 0.15),
                                borderRadius: BorderRadius.circular(14),
                              ),
                              child: const Icon(Icons.emergency_rounded, color: AppColors.error, size: 26),
                            ),
                            const SizedBox(width: 16),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text('Emergency Contacts', style: AppTypography.headingMd.copyWith(color: Colors.white)),
                                  Text(_info?['country']?.toString() ?? '',
                                      style: AppTypography.bodySm.copyWith(color: AppColors.textSecondary)),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 20),

                      // Hotlines
                      if (_info?['hotlines'] != null) ...[
                        Text('Hotlines', style: AppTypography.headingMd.copyWith(color: Colors.white)),
                        const SizedBox(height: 12),
                        ..._buildHotlines(_info!['hotlines']),
                        const SizedBox(height: 20),
                      ],

                      // Online Resources
                      if (_info?['online_resources'] != null) ...[
                        Text('Online Resources', style: AppTypography.headingMd.copyWith(color: Colors.white)),
                        const SizedBox(height: 12),
                        ..._buildResources(_info!['online_resources']),
                      ],
                    ],
                  ),
                ),
    );
  }

  List<Widget> _buildHotlines(dynamic hotlines) {
    if (hotlines is List) {
      return hotlines.map<Widget>((h) {
        if (h is Map) {
          return Padding(
            padding: const EdgeInsets.only(bottom: 10),
            child: GlassCard(
              padding: const EdgeInsets.all(16),
              child: Row(
                children: [
                  const Icon(Icons.phone_rounded, color: AppColors.royalBlue, size: 20),
                  const SizedBox(width: 14),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(h['name']?.toString() ?? '', style: AppTypography.bodyLg.copyWith(color: Colors.white)),
                        Text((h['phone'] ?? h['number'])?.toString() ?? '', style: AppTypography.bodyMd.copyWith(color: AppColors.gold)),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          );
        }
        return Padding(
          padding: const EdgeInsets.only(bottom: 8),
          child: Text(h.toString(), style: AppTypography.bodyMd.copyWith(color: Colors.white)),
        );
      }).toList();
    }
    if (hotlines is Map) {
      return hotlines.entries.map<Widget>((e) => Padding(
        padding: const EdgeInsets.only(bottom: 10),
        child: GlassCard(
          padding: const EdgeInsets.all(16),
          child: Row(
            children: [
              const Icon(Icons.phone_rounded, color: AppColors.royalBlue, size: 20),
              const SizedBox(width: 14),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(e.key.toString(), style: AppTypography.bodyLg.copyWith(color: Colors.white)),
                    Text(e.value.toString(), style: AppTypography.bodyMd.copyWith(color: AppColors.gold)),
                  ],
                ),
              ),
            ],
          ),
        ),
      )).toList();
    }
    return [Text(hotlines.toString(), style: AppTypography.bodyMd.copyWith(color: Colors.white))];
  }

  List<Widget> _buildResources(dynamic resources) {
    if (resources is List) {
      return resources.map<Widget>((r) {
        if (r is Map) {
          return Padding(
            padding: const EdgeInsets.only(bottom: 10),
            child: GlassCard(
              padding: const EdgeInsets.all(16),
              child: Row(
                children: [
                  const Icon(Icons.language_rounded, color: AppColors.gold, size: 20),
                  const SizedBox(width: 14),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(r['name']?.toString() ?? '', style: AppTypography.bodyLg.copyWith(color: Colors.white)),
                        if (r['url'] != null)
                          Text(r['url'].toString(), style: AppTypography.bodySm.copyWith(color: AppColors.royalBlue)),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          );
        }
        return Padding(
          padding: const EdgeInsets.only(bottom: 8),
          child: Text(r.toString(), style: AppTypography.bodyMd.copyWith(color: Colors.white)),
        );
      }).toList();
    }
    if (resources is Map) {
      return resources.entries.map<Widget>((e) => Padding(
        padding: const EdgeInsets.only(bottom: 10),
        child: GlassCard(
          padding: const EdgeInsets.all(16),
          child: Row(
            children: [
              const Icon(Icons.language_rounded, color: AppColors.gold, size: 20),
              const SizedBox(width: 14),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(e.key.toString(), style: AppTypography.bodyLg.copyWith(color: Colors.white)),
                    Text(e.value.toString(), style: AppTypography.bodySm.copyWith(color: AppColors.royalBlue)),
                  ],
                ),
              ),
            ],
          ),
        ),
      )).toList();
    }
    return [Text(resources.toString(), style: AppTypography.bodyMd.copyWith(color: Colors.white))];
  }
}
