import 'package:flutter/material.dart';

import '../../../../core/services/market_offline_service.dart';
import 'market_offline_widgets.dart';

const Color _green = Color.fromARGB(255, 2, 105, 48);
const Color _gold = Color.fromARGB(255, 204, 117, 4);
const Color _border = Color(0xFFE3E7EC);
const Color _muted = Color(0xFF66727E);

class ReportedMarketSubTab extends StatefulWidget {
  final String currentUserName;

  const ReportedMarketSubTab({super.key, required this.currentUserName});

  @override
  State<ReportedMarketSubTab> createState() => _ReportedMarketSubTabState();
}

class _ReportedMarketSubTabState extends State<ReportedMarketSubTab> {
  List<MarketItem> _items = const <MarketItem>[];
  bool _loading = true;
  bool _reading=false;
  String? _error;
  String _filter = 'all';

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

  @override void dispose(){MarketOfflineService.revision.removeListener(_load);super.dispose();}
  Future<void> _refreshNow()async{await MarketOfflineService.sync(force:true);await _load();}
  Future<void> _load() async {
    if (!mounted||_reading) return;
    _reading=true;
    setState(() {
      _loading = _items.isEmpty;
      _error = null;
    });
    try {
      final page = await MarketOfflineService.getItems(status: 'all', moderation: true, limit: 50);
      if (!mounted) return;
      setState(() {
        _items = page.items;
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loading = false;
        _items=const <MarketItem>[];
        _error = _cleanError(e);
      });
    } finally {_reading=false;}
  }

  Future<void> _moderate(MarketItem item, String action) async {
    try {
      await MarketOfflineService.moderateItem(item.id, action);
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(action == 'reject' ? 'Listing rejected.' : 'Listing approved and returned to the marketplace.'), backgroundColor: _green, behavior: SnackBarBehavior.floating));
      await _load();
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(_cleanError(e)), backgroundColor: Colors.red.shade700, behavior: SnackBarBehavior.floating));
    }
  }

  @override
  Widget build(BuildContext context) {
    final visible = _items.where((item) => _filter == 'all' || item.status.toLowerCase() == _filter).toList();
    return RefreshIndicator(
      color: _green,
      onRefresh: _refreshNow,
      child: ListView(
        physics: const AlwaysScrollableScrollPhysics(),
        padding: const EdgeInsets.only(bottom: 80),
        children: [
          const MarketSyncBar(),
          const SizedBox(height:8),
          Container(
            padding: const EdgeInsets.all(18),
            decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(24), border: Border.all(color: _border)),
            child: Row(children: [Container(width: 48, height: 48, decoration: BoxDecoration(color: Colors.orange.withOpacity(0.1), borderRadius: BorderRadius.circular(15)), child: const Icon(Icons.admin_panel_settings_outlined, color: Colors.orange)), const SizedBox(width: 12), const Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text('Marketplace Moderation', style: TextStyle(fontSize: 21, fontWeight: FontWeight.w900)), SizedBox(height: 4), Text('Approve new listings and review content reported by the community.', style: TextStyle(color: _muted, fontSize: 12))])), PopupMenuButton<String>(initialValue: _filter, onSelected: (v) => setState(() => _filter = v), itemBuilder: (_) => const [PopupMenuItem(value: 'all', child: Text('All moderation')), PopupMenuItem(value: 'pending', child: Text('Pending approval')), PopupMenuItem(value: 'reported', child: Text('Reported'))], child: Container(padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 9), decoration: BoxDecoration(color: const Color(0xFFF7F9FA), borderRadius: BorderRadius.circular(12), border: Border.all(color: _border)), child: Text(_filter == 'all' ? 'All' : _filter.toUpperCase(), style: const TextStyle(fontSize: 10, fontWeight: FontWeight.w900))) )]),
          ),
          const SizedBox(height: 14),
          if (_loading)
            const Padding(padding: EdgeInsets.symmetric(vertical: 120), child: Center(child: CircularProgressIndicator(color: _green)))
          else if (_error != null)
            Container(padding: const EdgeInsets.all(26), decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(22), border: Border.all(color: Colors.red.shade200)), child: Column(children: [Icon(Icons.lock_outline, size: 42, color: Colors.red.shade300), const SizedBox(height: 10), Text(_error!, textAlign: TextAlign.center), const SizedBox(height: 12), FilledButton(onPressed: _load, child: const Text('Retry'))]))
          else if (visible.isEmpty)
            Container(padding: const EdgeInsets.symmetric(vertical: 70), decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(22), border: Border.all(color: _border)), child: Column(children: [Icon(Icons.verified_outlined, size: 58, color: Colors.grey.shade300), const SizedBox(height: 12), const Text('Nothing requires moderation.', style: TextStyle(fontWeight: FontWeight.w900))]))
          else
            ...visible.map((item) => Padding(padding: const EdgeInsets.only(bottom: 12), child: _ModerationCard(item: item, onApprove: () => _moderate(item, item.status.toLowerCase() == 'reported' ? 'restore' : 'approve'), onReject: () => _moderate(item, 'reject')))),
        ],
      ),
    );
  }
}

class _ModerationCard extends StatelessWidget {
  final MarketItem item;
  final VoidCallback onApprove;
  final VoidCallback onReject;

  const _ModerationCard({required this.item, required this.onApprove, required this.onReject});

  @override
  Widget build(BuildContext context) {
    final reported = item.status.toLowerCase() == 'reported';
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(12), border: Border.all(color: reported ? Colors.red.shade200 : Colors.orange.shade200)),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Row(children: [Icon(reported ? Icons.flag_rounded : Icons.hourglass_top_rounded, color: reported ? Colors.red.shade700 : Colors.orange.shade800), const SizedBox(width: 8), Expanded(child: Text(item.title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w900))), Container(padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 6), decoration: BoxDecoration(color: (reported ? Colors.red : Colors.orange).withOpacity(0.08), borderRadius: BorderRadius.circular(99)), child: Text(item.status.toUpperCase(), style: TextStyle(fontSize: 9, fontWeight: FontWeight.w900, color: reported ? Colors.red.shade700 : Colors.orange.shade800)))]),
        const SizedBox(height: 8),
        Text('K ${item.price.toStringAsFixed(2)} • ${item.category} • ${item.condition}', style: const TextStyle(color: _green, fontWeight: FontWeight.w800)),
        const SizedBox(height: 7),
        Text('Seller: ${item.sellerName}${item.campus.isEmpty ? '' : ' • ${item.campus}'}', style: const TextStyle(color: _muted, fontSize: 11.5)),
        const SizedBox(height: 8),
        Text(item.description, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _muted, height: 1.3)),
        if (reported && item.reportReason.isNotEmpty) ...[const SizedBox(height: 10), Container(width: double.infinity, padding: const EdgeInsets.all(11), decoration: BoxDecoration(color: Colors.red.shade50, borderRadius: BorderRadius.circular(12)), child: Text('Reported because: ${item.reportReason}', style: TextStyle(color: Colors.red.shade900, fontSize: 11.5, fontWeight: FontWeight.w700)))],
        const SizedBox(height: 8),
        Wrap(spacing: 8, runSpacing: 8, children: [FilledButton.icon(onPressed: onApprove, style: FilledButton.styleFrom(backgroundColor: _green), icon: const Icon(Icons.check_circle_outline), label: Text(reported ? 'Restore listing' : 'Approve listing')), OutlinedButton.icon(onPressed: onReject, style: OutlinedButton.styleFrom(foregroundColor: Colors.red.shade700), icon: const Icon(Icons.block_outlined), label: const Text('Reject'))]),
      ]),
    );
  }
}

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