import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

/// Payload from api/version: only keys with non-empty URLs are shown as options.
class UpdateRequiredPayload {
  UpdateRequiredPayload({
    required this.storeUrls,
    this.onRetry,
  });

  final Map<String, String?> storeUrls;
  final VoidCallback? onRetry;

  /// Build from API response data.store_urls (map with nullable string values).
  static UpdateRequiredPayload fromJson(Map<String, dynamic>? storeUrlsJson, {VoidCallback? onRetry}) {
    final Map<String, String?> urls = {};
    if (storeUrlsJson != null) {
      for (final entry in storeUrlsJson.entries) {
        final v = entry.value;
        final s = v is String ? (v.trim().isEmpty ? null : v.trim()) : null;
        if (s != null) {
          urls[entry.key] = s;
        }
      }
    }
    return UpdateRequiredPayload(storeUrls: urls, onRetry: onRetry);
  }

  List<_StoreOption> get visibleOptions {
    const labels = {
      'direct_apk': 'Download APK',
      'google_play': 'Google Play',
      'app_store': 'App Store',
      'huawei_app_gallery': 'Huawei AppGallery',
    };
    final list = <_StoreOption>[];
    for (final key in ['direct_apk', 'google_play', 'app_store', 'huawei_app_gallery']) {
      final url = storeUrls[key];
      if (url != null && url.isNotEmpty) {
        list.add(_StoreOption(label: labels[key] ?? key, url: url));
      }
    }
    return list;
  }
}

class _StoreOption {
  const _StoreOption({required this.label, required this.url});
  final String label;
  final String url;
}

class UpdateRequiredScreen extends StatelessWidget {
  const UpdateRequiredScreen({super.key, required this.payload});

  final UpdateRequiredPayload payload;

  Future<void> _openUrl(String url) async {
    final uri = Uri.tryParse(url);
    if (uri != null && await canLaunchUrl(uri)) {
      await launchUrl(uri, mode: LaunchMode.externalApplication);
    }
  }

  @override
  Widget build(BuildContext context) {
    final options = payload.visibleOptions;
    final hasRetry = payload.onRetry != null;

    return PopScope(
      canPop: false,
      child: Scaffold(
        backgroundColor: const Color(0xFF0F1114),
        body: SafeArea(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 24),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  width: 88,
                  height: 88,
                  decoration: BoxDecoration(
                    color: const Color(0x33FF9500),
                    borderRadius: BorderRadius.circular(24),
                    border: Border.all(
                      color: const Color(0xFFFF9500).withOpacity(0.4),
                      width: 2,
                    ),
                  ),
                  child: const Icon(
                    Icons.system_update_rounded,
                    color: Color(0xFFFF9500),
                    size: 44,
                  ),
                ),
                const SizedBox(height: 28),
                const Text(
                  'Update required',
                  style: TextStyle(
                    fontFamily: 'RobotoMono',
                    color: Color(0xFFF2F2F2),
                    fontSize: 24,
                    fontWeight: FontWeight.w700,
                  ),
                ),
                const SizedBox(height: 12),
                const Text(
                  'A new version of the app is available. Please update to continue.',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: Color(0xFF8A8F99),
                    fontSize: 15,
                    height: 1.5,
                  ),
                ),
                const SizedBox(height: 32),
                if (options.isEmpty)
                  const Text(
                    'Please contact support or try again later.',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: Color(0xFF8A8F99),
                      fontSize: 14,
                    ),
                  )
                else
                  ...options.map((opt) => Padding(
                        padding: const EdgeInsets.only(bottom: 12),
                        child: SizedBox(
                          width: double.infinity,
                          height: 54,
                          child: FilledButton(
                            onPressed: () => _openUrl(opt.url),
                            child: Text(opt.label),
                          ),
                        ),
                      )),
                if (hasRetry) ...[
                  const SizedBox(height: 16),
                  TextButton(
                    onPressed: payload.onRetry,
                    child: const Text('Retry'),
                  ),
                ],
              ],
            ),
          ),
        ),
      ),
    );
  }
}
