// lib/features/admin/tabs/messages/channels_utils.dart

import 'dart:io';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import '../../../../core/networks/api_client.dart';

// 🚀 CENTRALIZED THEME COLORS
class FbFeedColors {
  static const Color blue = Color.fromARGB(255, 2, 105, 48); 
  static const Color bg = Color(0xFFF4F7F5);
  static const Color textMain = Color(0xFF17231C);
  static const Color textSecondary = Color(0xFF66756C);
  static const Color divider = Color(0xFFE0E8E3);
  static const Color gold = Color.fromARGB(255, 204, 117, 4);
}

// 🚀 TOP LEVEL ISOLATE FUNCTION FOR PARSING
List<dynamic> parseFbPostsJson(String text) {
  final parsed = json.decode(text);
  return parsed is List ? parsed : (parsed['data'] ?? parsed['posts'] ?? []);
}

// 🚀 CUSTOM IMAGE CACHE MANAGER (Sits in computer folder)
final CacheManager fbFeedCacheManager = CacheManager(
  Config('fbFeedImageCache', stalePeriod: const Duration(days: 30), maxNrOfCacheObjects: 500),
);

// =====================================================================
// 🚀 NEW SAFE IMAGE BUILDERS (PREVENTS ALL 404 CRASHES)
// =====================================================================


Widget _defaultMediaError(double? width, double? height) {
  return Container(
    width: width,
    height: height ?? 180,
    color: const Color(0xFFF0F2F5),
    alignment: Alignment.center,
    child: const Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(Icons.broken_image_outlined, color: Color(0xFF8A9490), size: 30),
        SizedBox(height: 6),
        Text('Media could not be displayed', style: TextStyle(color: Color(0xFF66756C), fontSize: 12, fontWeight: FontWeight.w600)),
      ],
    ),
  );
}

Widget buildSmartFbImage(String? imageUrl, {double? width, double? height, BoxFit fit = BoxFit.cover, Widget? errorWidget}) {
  if (imageUrl == null || imageUrl.trim().isEmpty) return errorWidget ?? _defaultMediaError(width, height);
  final String trimmed = imageUrl.trim();

  // 1. Network URLs
  if (trimmed.startsWith('http://') || trimmed.startsWith('https://')) {
    return CachedNetworkImage(
      imageUrl: trimmed, width: width, height: height, fit: fit,
      cacheManager: fbFeedCacheManager,
      errorWidget: (context, url, error) => errorWidget ?? _defaultMediaError(width, height),
    );
  } 
  
  // 2. Relative Server Uploads (Strips api/v1 to avoid broken routing)
  if (trimmed.startsWith('/uploads') || trimmed.startsWith('/static') || trimmed.startsWith('uploads/') || trimmed.startsWith('static/')) {
    String base = ApiClient.baseUrl;
    if (base.endsWith('/api/v1')) base = base.replaceAll('/api/v1', '');
    final fullUrl = '$base${trimmed.startsWith('/') ? '' : '/'}$trimmed';
    
    return CachedNetworkImage(
      imageUrl: fullUrl, width: width, height: height, fit: fit,
      cacheManager: fbFeedCacheManager,
      errorWidget: (context, url, error) => errorWidget ?? _defaultMediaError(width, height),
    );
  }

  // 3. Local Computer/Phone File Paths
  if (trimmed.startsWith('/data') || trimmed.startsWith('/storage') || trimmed.startsWith('C:\\') || trimmed.startsWith('file://')) {
    try {
      final cleanPath = trimmed.startsWith('file://') ? trimmed.replaceFirst('file://', '') : trimmed;
      return Image.file(File(cleanPath), width: width, height: height, fit: fit, errorBuilder: (_,__,___) => errorWidget ?? _defaultMediaError(width, height));
    } catch (_) { return errorWidget ?? _defaultMediaError(width, height); }
  } 

  // 4. Base64 Fallback
  try {
    String cleanBase64 = trimmed.contains(',') ? trimmed.split(',').last : trimmed;
    return Image.memory(base64Decode(cleanBase64.replaceAll(RegExp(r'\s+'), '')), width: width, height: height, fit: fit, errorBuilder: (_,__,___) => errorWidget ?? _defaultMediaError(width, height));
  } catch (e) { return errorWidget ?? _defaultMediaError(width, height); }
}

Widget buildSmartFbAvatar(String? imageUrl, String fallbackName, {double radius = 20}) {
  final fallbackChar = fallbackName.isNotEmpty ? fallbackName[0].toUpperCase() : 'U';
  return ClipOval(
    child: Container(
      width: radius * 2,
      height: radius * 2,
      color: Colors.grey.shade300,
      child: imageUrl != null && imageUrl.trim().isNotEmpty
          ? buildSmartFbImage(
              imageUrl, 
              fit: BoxFit.cover, 
              errorWidget: Center(child: Text(fallbackChar, style: const TextStyle(color: FbFeedColors.blue, fontWeight: FontWeight.bold)))
            )
          : Center(child: Text(fallbackChar, style: const TextStyle(color: FbFeedColors.blue, fontWeight: FontWeight.bold))),
    ),
  );
}

// 🚀 UPDATED ZOOMABLE IMAGE VIEWER
void showZoomableImage(BuildContext context, String? imageUrl) {
  if (imageUrl == null || imageUrl.isEmpty) return;
  showDialog(
    context: context,
    barrierColor: Colors.black.withOpacity(0.95),
    builder: (ctx) => Dialog(
      backgroundColor: Colors.transparent, insetPadding: EdgeInsets.zero,
      child: Stack(
        fit: StackFit.expand,
        children: [
          InteractiveViewer(panEnabled: true, minScale: 0.5, maxScale: 4.0, child: buildSmartFbImage(imageUrl, fit: BoxFit.contain)),
          Positioned(top: 24, right: 24, child: IconButton(icon: const Icon(Icons.close_rounded, color: Colors.white, size: 32), onPressed: () => Navigator.pop(ctx))),
        ],
      ),
    ),
  );
}