import 'dart:convert';

import 'package:flutter/material.dart';

import '../../../../core/services/campus_market_service.dart';

const Color marketAdminGreen = Color.fromARGB(255, 2, 105, 48);
const Color marketAdminGold = Color.fromARGB(255, 204, 117, 4);
const Color marketAdminBg = Color(0xFFF4F6F8);
const Color marketAdminBorder = Color(0xFFE3E8ED);
const Color marketAdminText = Color(0xFF17242D);
const Color marketAdminMuted = Color(0xFF677681);

class MarketAdminItemCard extends StatelessWidget {
  final MarketItem item;
  final String statusLabel;
  final Color statusColor;
  final VoidCallback onOpen;
  final Widget? footer;
  final bool showReportReason;

  const MarketAdminItemCard({
    super.key,
    required this.item,
    required this.statusLabel,
    required this.statusColor,
    required this.onOpen,
    this.footer,
    this.showReportReason = false,
  });

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.white,
      borderRadius: BorderRadius.circular(20),
      child: InkWell(
        onTap: onOpen,
        borderRadius: BorderRadius.circular(20),
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20),
            border: Border.all(color: marketAdminBorder),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.025),
                blurRadius: 16,
                offset: const Offset(0, 5),
              ),
            ],
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              _AdminListingImage(item: item),
              Padding(
                padding: const EdgeInsets.all(15),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Container(
                          padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5),
                          decoration: BoxDecoration(
                            color: statusColor.withOpacity(0.10),
                            borderRadius: BorderRadius.circular(999),
                          ),
                          child: Text(
                            statusLabel.toUpperCase(),
                            style: TextStyle(
                              color: statusColor,
                              fontSize: 9,
                              letterSpacing: .5,
                              fontWeight: FontWeight.w900,
                            ),
                          ),
                        ),
                        const Spacer(),
                        Text(
                          _timeAgo(item.createdAt),
                          style: const TextStyle(
                            color: marketAdminMuted,
                            fontSize: 10,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 10),
                    Text(
                      item.title,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(
                        color: marketAdminText,
                        fontSize: 16,
                        height: 1.25,
                        fontWeight: FontWeight.w900,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      _money(item.price),
                      style: const TextStyle(
                        color: marketAdminGreen,
                        fontSize: 20,
                        fontWeight: FontWeight.w900,
                      ),
                    ),
                    const SizedBox(height: 10),
                    _MetaRow(icon: Icons.person_outline_rounded, value: item.sellerName),
                    const SizedBox(height: 5),
                    _MetaRow(
                      icon: Icons.location_on_outlined,
                      value: [item.campus, item.location].where((v) => v.trim().isNotEmpty).join(' • '),
                      fallback: 'Campus/location not specified',
                    ),
                    const SizedBox(height: 5),
                    _MetaRow(
                      icon: Icons.inventory_2_outlined,
                      value: '${item.condition} • Qty ${item.quantity}',
                    ),
                    if (showReportReason && item.reportReason.trim().isNotEmpty) ...[
                      const SizedBox(height: 11),
                      Container(
                        width: double.infinity,
                        padding: const EdgeInsets.all(10),
                        decoration: BoxDecoration(
                          color: Colors.red.shade50,
                          borderRadius: BorderRadius.circular(12),
                          border: Border.all(color: Colors.red.shade100),
                        ),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Icon(Icons.flag_outlined, size: 16, color: Colors.red.shade700),
                            const SizedBox(width: 7),
                            Expanded(
                              child: Text(
                                item.reportReason,
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                  color: Colors.red.shade900,
                                  fontSize: 10.5,
                                  height: 1.4,
                                  fontWeight: FontWeight.w700,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                    const SizedBox(height: 12),
                    Row(
                      children: [
                        _SmallStat(icon: Icons.favorite_border_rounded, value: '${item.likeCount}'),
                        const SizedBox(width: 12),
                        _SmallStat(icon: Icons.mode_comment_outlined, value: '${item.commentCount}'),
                        const SizedBox(width: 12),
                        _SmallStat(icon: Icons.mark_email_unread_outlined, value: '${item.inquiryCount}'),
                      ],
                    ),
                    if (footer != null) ...[
                      const SizedBox(height: 14),
                      const Divider(height: 1),
                      const SizedBox(height: 12),
                      footer!,
                    ],
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class MarketAdminEmptyState extends StatelessWidget {
  final IconData icon;
  final String title;
  final String message;
  final VoidCallback? onRefresh;

  const MarketAdminEmptyState({
    super.key,
    required this.icon,
    required this.title,
    required this.message,
    this.onRefresh,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 70),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(22),
        border: Border.all(color: marketAdminBorder),
      ),
      child: Column(
        children: [
          Container(
            width: 64,
            height: 64,
            decoration: BoxDecoration(
              color: marketAdminGreen.withOpacity(.06),
              shape: BoxShape.circle,
            ),
            child: Icon(icon, size: 31, color: marketAdminGreen),
          ),
          const SizedBox(height: 16),
          Text(title, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w900, color: marketAdminText)),
          const SizedBox(height: 7),
          Text(message, textAlign: TextAlign.center, style: const TextStyle(color: marketAdminMuted, height: 1.5)),
          if (onRefresh != null) ...[
            const SizedBox(height: 18),
            OutlinedButton.icon(
              onPressed: onRefresh,
              icon: const Icon(Icons.refresh_rounded),
              label: const Text('Refresh'),
              style: OutlinedButton.styleFrom(foregroundColor: marketAdminGreen),
            ),
          ],
        ],
      ),
    );
  }
}

class MarketAdminErrorState extends StatelessWidget {
  final String message;
  final VoidCallback onRetry;

  const MarketAdminErrorState({super.key, required this.message, required this.onRetry});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 60),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(22),
        border: Border.all(color: Colors.red.shade100),
      ),
      child: Column(
        children: [
          Icon(Icons.cloud_off_rounded, size: 48, color: Colors.red.shade300),
          const SizedBox(height: 12),
          const Text('Unable to load marketplace', style: TextStyle(fontSize: 17, fontWeight: FontWeight.w900)),
          const SizedBox(height: 8),
          Text(message, textAlign: TextAlign.center, style: const TextStyle(color: marketAdminMuted, height: 1.5)),
          const SizedBox(height: 15),
          FilledButton.icon(
            onPressed: onRetry,
            style: FilledButton.styleFrom(backgroundColor: marketAdminGreen),
            icon: const Icon(Icons.refresh_rounded),
            label: const Text('Try Again'),
          ),
        ],
      ),
    );
  }
}

class MarketAdminFilters extends StatelessWidget {
  final TextEditingController searchController;
  final List<String> campuses;
  final String campus;
  final String category;
  final ValueChanged<String> onCampusChanged;
  final ValueChanged<String> onCategoryChanged;
  final VoidCallback onSearch;
  final VoidCallback onRefresh;

  const MarketAdminFilters({
    super.key,
    required this.searchController,
    required this.campuses,
    required this.campus,
    required this.category,
    required this.onCampusChanged,
    required this.onCategoryChanged,
    required this.onSearch,
    required this.onRefresh,
  });

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final compact = constraints.maxWidth < 760;
        final search = TextField(
          controller: searchController,
          textInputAction: TextInputAction.search,
          onSubmitted: (_) => onSearch(),
          decoration: _inputDecoration('Search item, seller or location...', Icons.search_rounded).copyWith(
            suffixIcon: IconButton(onPressed: onSearch, icon: const Icon(Icons.arrow_forward_rounded)),
          ),
        );
        final campusField = DropdownButtonFormField<String>(
          value: campus,
          isExpanded: true,
          decoration: _inputDecoration('Campus', Icons.location_on_outlined),
          items: ['All Campuses', ...campuses]
              .map((value) => DropdownMenuItem(value: value, child: Text(value, overflow: TextOverflow.ellipsis)))
              .toList(),
          onChanged: (value) {
            if (value != null) onCampusChanged(value);
          },
        );
        final categoryField = DropdownButtonFormField<String>(
          value: category,
          isExpanded: true,
          decoration: _inputDecoration('Category', Icons.category_outlined),
          items: ['All Categories', ...CampusMarketService.categories]
              .map((value) => DropdownMenuItem(value: value, child: Text(value, overflow: TextOverflow.ellipsis)))
              .toList(),
          onChanged: (value) {
            if (value != null) onCategoryChanged(value);
          },
        );

        return Container(
          padding: const EdgeInsets.all(13),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(18),
            border: Border.all(color: marketAdminBorder),
          ),
          child: compact
              ? Column(
                  children: [
                    search,
                    const SizedBox(height: 9),
                    campusField,
                    const SizedBox(height: 9),
                    categoryField,
                    const SizedBox(height: 9),
                    SizedBox(
                      width: double.infinity,
                      child: OutlinedButton.icon(
                        onPressed: onRefresh,
                        icon: const Icon(Icons.refresh_rounded),
                        label: const Text('Refresh'),
                      ),
                    ),
                  ],
                )
              : Row(
                  children: [
                    Expanded(flex: 3, child: search),
                    const SizedBox(width: 10),
                    Expanded(flex: 2, child: campusField),
                    const SizedBox(width: 10),
                    Expanded(flex: 2, child: categoryField),
                    const SizedBox(width: 10),
                    IconButton.outlined(onPressed: onRefresh, icon: const Icon(Icons.refresh_rounded)),
                  ],
                ),
        );
      },
    );
  }
}

Future<void> showMarketAdminDetails(
  BuildContext context,
  MarketItem item, {
  Widget? actions,
}) async {
  await showDialog<void>(
    context: context,
    builder: (_) => Dialog(
      backgroundColor: Colors.transparent,
      insetPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 16),
      child: Container(
        constraints: BoxConstraints(
          maxWidth: 900,
          maxHeight: MediaQuery.of(context).size.height * .92,
        ),
        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(24)),
        child: Column(
          children: [
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 14),
              decoration: const BoxDecoration(
                color: marketAdminGreen,
                borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
              ),
              child: Row(
                children: [
                  const Icon(Icons.fact_check_outlined, color: Colors.white),
                  const SizedBox(width: 9),
                  const Expanded(
                    child: Text('Listing Review', style: TextStyle(color: Colors.white, fontSize: 17, fontWeight: FontWeight.w900)),
                  ),
                  IconButton(onPressed: () => Navigator.pop(context), icon: const Icon(Icons.close_rounded, color: Colors.white)),
                ],
              ),
            ),
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(20),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _DetailImageGallery(item: item),
                    const SizedBox(height: 18),
                    Wrap(
                      spacing: 8,
                      runSpacing: 8,
                      children: [
                        _DetailChip(icon: Icons.category_outlined, text: item.category),
                        _DetailChip(icon: Icons.inventory_2_outlined, text: item.condition),
                        _DetailChip(icon: Icons.numbers_rounded, text: 'Qty ${item.quantity}'),
                        _DetailChip(icon: Icons.schedule_rounded, text: _timeAgo(item.createdAt)),
                      ],
                    ),
                    const SizedBox(height: 16),
                    Text(item.title, style: const TextStyle(fontSize: 23, height: 1.25, fontWeight: FontWeight.w900, color: marketAdminText)),
                    const SizedBox(height: 8),
                    Text(_money(item.price), style: const TextStyle(color: marketAdminGreen, fontSize: 24, fontWeight: FontWeight.w900)),
                    const SizedBox(height: 15),
                    const Text('Description', style: TextStyle(fontWeight: FontWeight.w900, color: marketAdminText)),
                    const SizedBox(height: 6),
                    Text(item.description.isEmpty ? 'No description provided.' : item.description,
                        style: const TextStyle(color: marketAdminMuted, height: 1.65)),
                    const SizedBox(height: 18),
                    _AdminSellerPanel(item: item),
                    if (item.reportReason.trim().isNotEmpty) ...[
                      const SizedBox(height: 14),
                      Container(
                        width: double.infinity,
                        padding: const EdgeInsets.all(14),
                        decoration: BoxDecoration(
                          color: Colors.red.shade50,
                          borderRadius: BorderRadius.circular(15),
                          border: Border.all(color: Colors.red.shade100),
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                Icon(Icons.flag_rounded, size: 18, color: Colors.red.shade700),
                                const SizedBox(width: 7),
                                Text('Report reason', style: TextStyle(color: Colors.red.shade800, fontWeight: FontWeight.w900)),
                              ],
                            ),
                            const SizedBox(height: 7),
                            Text(item.reportReason, style: TextStyle(color: Colors.red.shade900, height: 1.5)),
                          ],
                        ),
                      ),
                    ],
                    const SizedBox(height: 16),
                    Row(
                      children: [
                        Expanded(child: _MetricBox(label: 'Likes', value: '${item.likeCount}', icon: Icons.favorite_border_rounded)),
                        const SizedBox(width: 8),
                        Expanded(child: _MetricBox(label: 'Comments', value: '${item.commentCount}', icon: Icons.mode_comment_outlined)),
                        const SizedBox(width: 8),
                        Expanded(child: _MetricBox(label: 'Inquiries', value: '${item.inquiryCount}', icon: Icons.mark_email_unread_outlined)),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            if (actions != null)
              Container(
                width: double.infinity,
                padding: const EdgeInsets.all(14),
                decoration: const BoxDecoration(
                  color: Color(0xFFF7F9FA),
                  borderRadius: BorderRadius.vertical(bottom: Radius.circular(24)),
                ),
                child: actions,
              ),
          ],
        ),
      ),
    ),
  );
}

Widget marketAdminActionButton({
  required String label,
  required IconData icon,
  required VoidCallback? onPressed,
  Color? color,
  bool filled = true,
}) {
  final buttonColor = color ?? marketAdminGreen;
  if (filled) {
    return FilledButton.icon(
      onPressed: onPressed,
      style: FilledButton.styleFrom(backgroundColor: buttonColor, foregroundColor: Colors.white),
      icon: Icon(icon, size: 17),
      label: Text(label, style: const TextStyle(fontWeight: FontWeight.w800)),
    );
  }
  return OutlinedButton.icon(
    onPressed: onPressed,
    style: OutlinedButton.styleFrom(foregroundColor: buttonColor, side: BorderSide(color: buttonColor.withOpacity(.35))),
    icon: Icon(icon, size: 17),
    label: Text(label, style: const TextStyle(fontWeight: FontWeight.w800)),
  );
}

InputDecoration _inputDecoration(String hint, IconData icon) {
  return InputDecoration(
    hintText: hint,
    prefixIcon: Icon(icon, color: marketAdminGreen, size: 19),
    filled: true,
    fillColor: const Color(0xFFF8FAFB),
    isDense: true,
    contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 13),
    border: OutlineInputBorder(borderRadius: BorderRadius.circular(13), borderSide: const BorderSide(color: marketAdminBorder)),
    enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(13), borderSide: const BorderSide(color: marketAdminBorder)),
    focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(13), borderSide: const BorderSide(color: marketAdminGreen, width: 1.4)),
  );
}

class _AdminListingImage extends StatelessWidget {
  final MarketItem item;
  const _AdminListingImage({required this.item});

  @override
  Widget build(BuildContext context) {
    final count = item.images.length;
    return ClipRRect(
      borderRadius: const BorderRadius.vertical(top: Radius.circular(19)),
      child: Stack(
        children: [
          AspectRatio(
            aspectRatio: 16 / 10,
            child: _itemImage(item),
          ),
          if (count > 1)
            Positioned(
              right: 10,
              bottom: 10,
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 11, vertical: 7),
                decoration: BoxDecoration(color: Colors.black.withOpacity(.68), borderRadius: BorderRadius.circular(12)),
                child: Text('+${count - 1}', style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w900)),
              ),
            ),
        ],
      ),
    );
  }
}

class _DetailImageGallery extends StatelessWidget {
  final MarketItem item;
  const _DetailImageGallery({required this.item});

  @override
  Widget build(BuildContext context) {
    if (item.images.isEmpty) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(18),
        child: AspectRatio(aspectRatio: 16 / 8, child: _itemImage(item)),
      );
    }
    return SizedBox(
      height: 310,
      child: PageView.builder(
        itemCount: item.images.length,
        itemBuilder: (_, index) {
          final media = item.images[index];
          final path = media.path.isNotEmpty ? media.path : media.thumbnailPath;
          return Padding(
            padding: const EdgeInsets.only(right: 8),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(18),
              child: Image.network(
                CampusMarketService.mediaUrl(path),
                fit: BoxFit.cover,
                errorBuilder: (_, __, ___) => _fallbackImage(),
              ),
            ),
          );
        },
      ),
    );
  }
}

Widget _itemImage(MarketItem item) {
  if (item.images.isNotEmpty) {
    final first = item.images.first;
    final source = first.thumbnailPath.trim().isNotEmpty ? first.thumbnailPath : first.path;
    return Image.network(
      CampusMarketService.mediaUrl(source),
      fit: BoxFit.cover,
      errorBuilder: (_, __, ___) => _fallbackImage(),
    );
  }

  final legacy = item.legacyImageUrl.trim();
  if (legacy.isEmpty) return _fallbackImage();
  if (legacy.startsWith('http://') || legacy.startsWith('https://') || CampusMarketService.isStoredPath(legacy)) {
    return Image.network(
      CampusMarketService.mediaUrl(legacy),
      fit: BoxFit.cover,
      errorBuilder: (_, __, ___) => _fallbackImage(),
    );
  }
  try {
    var raw = legacy;
    if (raw.contains(',')) raw = raw.split(',').last;
    return Image.memory(base64Decode(raw.replaceAll(RegExp(r'\s+'), '')), fit: BoxFit.cover, errorBuilder: (_, __, ___) => _fallbackImage());
  } catch (_) {
    return _fallbackImage();
  }
}

Widget _fallbackImage() {
  return Container(
    color: const Color(0xFFF0F3F5),
    alignment: Alignment.center,
    child: Icon(Icons.storefront_outlined, size: 55, color: Colors.grey.shade400),
  );
}

class _MetaRow extends StatelessWidget {
  final IconData icon;
  final String value;
  final String fallback;
  const _MetaRow({required this.icon, required this.value, this.fallback = 'Not specified'});

  @override
  Widget build(BuildContext context) {
    final text = value.trim().isEmpty ? fallback : value;
    return Row(
      children: [
        Icon(icon, size: 14, color: marketAdminMuted),
        const SizedBox(width: 5),
        Expanded(child: Text(text, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: marketAdminMuted, fontSize: 11))),
      ],
    );
  }
}

class _SmallStat extends StatelessWidget {
  final IconData icon;
  final String value;
  const _SmallStat({required this.icon, required this.value});

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(icon, size: 15, color: marketAdminMuted),
        const SizedBox(width: 4),
        Text(value, style: const TextStyle(color: marketAdminMuted, fontSize: 10.5, fontWeight: FontWeight.w700)),
      ],
    );
  }
}

class _AdminSellerPanel extends StatelessWidget {
  final MarketItem item;
  const _AdminSellerPanel({required this.item});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: const Color(0xFFF7F9FA),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: marketAdminBorder),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text('Seller information', style: TextStyle(fontWeight: FontWeight.w900, color: marketAdminText)),
          const SizedBox(height: 10),
          _MetaRow(icon: Icons.person_outline_rounded, value: item.sellerName),
          const SizedBox(height: 7),
          _MetaRow(icon: Icons.badge_outlined, value: item.sellerRole),
          const SizedBox(height: 7),
          _MetaRow(icon: Icons.phone_outlined, value: item.sellerPhone, fallback: 'No phone provided'),
          const SizedBox(height: 7),
          _MetaRow(icon: Icons.location_on_outlined, value: [item.campus, item.location].where((v) => v.trim().isNotEmpty).join(' • ')),
        ],
      ),
    );
  }
}

class _DetailChip extends StatelessWidget {
  final IconData icon;
  final String text;
  const _DetailChip({required this.icon, required this.text});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7),
      decoration: BoxDecoration(color: const Color(0xFFF4F6F7), borderRadius: BorderRadius.circular(999)),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 14, color: marketAdminMuted),
          const SizedBox(width: 5),
          Text(text, style: const TextStyle(color: marketAdminMuted, fontSize: 10.5, fontWeight: FontWeight.w700)),
        ],
      ),
    );
  }
}

class _MetricBox extends StatelessWidget {
  final String label;
  final String value;
  final IconData icon;
  const _MetricBox({required this.label, required this.value, required this.icon});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 8),
      decoration: BoxDecoration(color: const Color(0xFFF7F9FA), borderRadius: BorderRadius.circular(13), border: Border.all(color: marketAdminBorder)),
      child: Column(
        children: [
          Icon(icon, size: 18, color: marketAdminGreen),
          const SizedBox(height: 5),
          Text(value, style: const TextStyle(fontWeight: FontWeight.w900, color: marketAdminText)),
          Text(label, style: const TextStyle(fontSize: 9.5, color: marketAdminMuted)),
        ],
      ),
    );
  }
}

String _money(double price) => 'K ${price.toStringAsFixed(2)}';

String _timeAgo(DateTime value) {
  final diff = DateTime.now().difference(value.toLocal());
  if (diff.inSeconds < 60) return 'Just now';
  if (diff.inMinutes < 60) return '${diff.inMinutes}m ago';
  if (diff.inHours < 24) return '${diff.inHours}h ago';
  if (diff.inDays < 7) return '${diff.inDays}d ago';
  return '${value.day.toString().padLeft(2, '0')}/${value.month.toString().padLeft(2, '0')}/${value.year}';
}

String marketAdminCleanError(Object error) {
  var value = error.toString();
  if (value.startsWith('Exception: ')) value = value.substring(11);
  return value;
}
