import 'package:flutter/material.dart';

import '../../../../core/services/market_offline_service.dart';
import 'market_offline_widgets.dart';
import 'active_market_sub_tab.dart' show MarketListingComposerDialog;

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 MyMarketSubTab extends StatefulWidget {
  const MyMarketSubTab({super.key});

  @override
  State<MyMarketSubTab> createState() => _MyMarketSubTabState();
}

class _MyMarketSubTabState extends State<MyMarketSubTab> {
  List<MarketItem> _items = const <MarketItem>[];
  bool _loading = true;
  bool _reading=false;
  String? _error;

  @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', mine: true, limit: 50);
      if (!mounted) return;
      setState(() {
        _items = page.items;
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loading = false;
        _error = _items.isEmpty?_cleanError(e):null;
      });
    } finally {_reading=false;}
  }

  Future<void> _create() async {
    final result = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (_) => const MarketListingComposerDialog(),
    );
    if (result == true) await _load();
  }

  Future<void> _markSold(MarketItem item) async {
    try {
      await MarketOfflineService.queueAction('update',item.id,{'status':'sold'});
      if (!mounted) return;
      _snack('Mark-sold change saved to outbox.');
      await _load();
    } catch (e) {
      _snack(_cleanError(e), error: true);
    }
  }

  Future<void> _delete(MarketItem item) async {
    final ok = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        title: const Text('Delete listing?'),
        content: Text('Delete "${item.title}" permanently?'),
        actions: [
          TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Cancel')),
          FilledButton(onPressed: () => Navigator.pop(context, true), style: FilledButton.styleFrom(backgroundColor: Colors.red.shade700), child: const Text('Delete')),
        ],
      ),
    );
    if (ok != true) return;
    try {
      await MarketOfflineService.deleteItem(item.id);
      if (!mounted) return;
      setState(() => _items = _items.where((e) => e.id != item.id).toList());
      _snack('Listing deleted.');
    } catch (e) {
      _snack(_cleanError(e), error: true);
    }
  }

  Future<void> _edit(MarketItem item) async {
    final title = TextEditingController(text: item.title);
    final price = TextEditingController(text: item.price.toStringAsFixed(2));
    final description = TextEditingController(text: item.description);
    final location = TextEditingController(text: item.location);
    final phone = TextEditingController(text: item.sellerPhone);
    final quantity = TextEditingController(text: '${item.quantity}');
    var category = MarketOfflineService.categories.contains(item.category) ? item.category : MarketOfflineService.categories.last;
    var condition = MarketOfflineService.conditions.contains(item.condition) ? item.condition : MarketOfflineService.conditions[2];

    final changes = await showDialog<Map<String, dynamic>>(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setDialogState) => AlertDialog(
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(22)),
          title: const Text('Edit listing'),
          content: SizedBox(
            width: 650,
            child: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  TextField(controller: title, decoration: const InputDecoration(labelText: 'Item title', border: OutlineInputBorder())),
                  const SizedBox(height: 10),
                  Row(children: [Expanded(child: TextField(controller: price, keyboardType: const TextInputType.numberWithOptions(decimal: true), decoration: const InputDecoration(labelText: 'Price (K)', border: OutlineInputBorder()))), const SizedBox(width: 10), Expanded(child: TextField(controller: quantity, keyboardType: TextInputType.number, decoration: const InputDecoration(labelText: 'Quantity', border: OutlineInputBorder())))]),
                  const SizedBox(height: 10),
                  DropdownButtonFormField<String>(value: category, isExpanded: true, decoration: const InputDecoration(labelText: 'Category', border: OutlineInputBorder()), items: MarketOfflineService.categories.map((e) => DropdownMenuItem(value: e, child: Text(e))).toList(), onChanged: (v) { if (v != null) setDialogState(() => category = v); }),
                  const SizedBox(height: 10),
                  DropdownButtonFormField<String>(value: condition, isExpanded: true, decoration: const InputDecoration(labelText: 'Condition', border: OutlineInputBorder()), items: MarketOfflineService.conditions.map((e) => DropdownMenuItem(value: e, child: Text(e))).toList(), onChanged: (v) { if (v != null) setDialogState(() => condition = v); }),
                  const SizedBox(height: 10),
                  TextField(controller: phone, decoration: const InputDecoration(labelText: 'Contact phone', border: OutlineInputBorder())),
                  const SizedBox(height: 10),
                  TextField(controller: location, decoration: const InputDecoration(labelText: 'Pickup location', border: OutlineInputBorder())),
                  const SizedBox(height: 10),
                  TextField(controller: description, minLines: 4, maxLines: 8, decoration: const InputDecoration(labelText: 'Description', border: OutlineInputBorder())),
                ],
              ),
            ),
          ),
          actions: [
            TextButton(onPressed: () => Navigator.pop(context), child: const Text('Cancel')),
            FilledButton(
              onPressed: () {
                final parsedPrice = double.tryParse(price.text.trim());
                final parsedQty = int.tryParse(quantity.text.trim());
                if (title.text.trim().length < 3 || parsedPrice == null || parsedQty == null || parsedQty < 1 || description.text.trim().length < 5) return;
                Navigator.pop(context, {
                  'title': title.text.trim(),
                  'price': parsedPrice,
                  'description': description.text.trim(),
                  'category': category,
                  'condition': condition,
                  'quantity': parsedQty,
                  'location': location.text.trim(),
                  'seller_phone': phone.text.trim(),
                });
              },
              style: FilledButton.styleFrom(backgroundColor: _green),
              child: const Text('Save changes'),
            ),
          ],
        ),
      ),
    );

    title.dispose();
    price.dispose();
    description.dispose();
    location.dispose();
    phone.dispose();
    quantity.dispose();

    if (changes == null) return;
    try {
      await MarketOfflineService.queueAction('update',item.id,changes);
      if (!mounted) return;
      _snack('Changes saved to outbox.');
      await _load();
    } catch (e) {
      _snack(_cleanError(e), error: true);
    }
  }

  void _snack(String message, {bool error = false}) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message), backgroundColor: error ? Colors.red.shade700 : _green, behavior: SnackBarBehavior.floating));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _create,
        backgroundColor: _gold,
        foregroundColor: Colors.white,
        icon: const Icon(Icons.add_business_rounded),
        label: const Text('NEW LISTING', style: TextStyle(fontWeight: FontWeight.w900)),
      ),
      body: RefreshIndicator(
        color: _green,
        onRefresh: _refreshNow,
        child: ListView(
          physics: const AlwaysScrollableScrollPhysics(),
          padding: const EdgeInsets.fromLTRB(0, 0, 0, 100),
          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: _green.withOpacity(0.08), borderRadius: BorderRadius.circular(15)), child: const Icon(Icons.inventory_2_outlined, color: _green)), const SizedBox(width: 12), const Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text('My Listings', style: TextStyle(fontSize: 21, fontWeight: FontWeight.w900)), SizedBox(height: 4), Text('Manage your pending, active, reported and sold marketplace items.', style: TextStyle(color: _muted, fontSize: 12))]))]),
            ),
            const SizedBox(height: 14),
            if (_loading)
              const Padding(padding: EdgeInsets.symmetric(vertical: 120), child: Center(child: CircularProgressIndicator(color: _green)))
            else if (_error != null)
              _ErrorCard(message: _error!, onRetry: _load)
            else if (_items.isEmpty)
              _EmptyCard(onCreate: _create)
            else
              ..._items.map((item) => Padding(padding: const EdgeInsets.only(bottom: 12), child: _MineCard(item: item, onEdit: () => _edit(item), onSold: () => _markSold(item), onDelete: () => _delete(item)))),
          ],
        ),
      ),
    );
  }
}

class _MineCard extends StatelessWidget {
  final MarketItem item;
  final VoidCallback onEdit;
  final VoidCallback onSold;
  final VoidCallback onDelete;

  const _MineCard({required this.item, required this.onEdit, required this.onSold, required this.onDelete});

  @override
  Widget build(BuildContext context) {
    final statusColor = _statusColor(item.status);
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(12), border: Border.all(color: _border)),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Row(children: [Expanded(child: Text(item.title, style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w900))), const SizedBox(width: 8), Container(padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), decoration: BoxDecoration(color: statusColor.withOpacity(0.1), borderRadius: BorderRadius.circular(99)), child: Text(item.status.toUpperCase(), style: TextStyle(color: statusColor, fontWeight: FontWeight.w900, fontSize: 9)))]),
        const SizedBox(height: 7),
        Text('K ${item.price.toStringAsFixed(2)}', style: const TextStyle(color: _green, fontSize: 15, fontWeight: FontWeight.w900)),
        const SizedBox(height: 7),
        Text(item.description, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _muted, height: 1.3)),
        const SizedBox(height: 8),
        Wrap(spacing: 7, runSpacing: 7, children: [_Pill('${item.likeCount} likes'), _Pill('${item.commentCount} comments'), _Pill('${item.inquiryCount} inquiries'), _Pill('${item.images.length} photos')]),
        if (item.reportReason.isNotEmpty) ...[const SizedBox(height: 10), Container(width: double.infinity, padding: const EdgeInsets.all(10), decoration: BoxDecoration(color: Colors.orange.shade50, borderRadius: BorderRadius.circular(12)), child: Text('Report reason: ${item.reportReason}', style: TextStyle(color: Colors.orange.shade900, fontSize: 11)))],
        const SizedBox(height: 8),
        Wrap(spacing: 8, runSpacing: 8, children: [OutlinedButton.icon(onPressed: onEdit, icon: const Icon(Icons.edit_outlined), label: const Text('Edit'), style: OutlinedButton.styleFrom(foregroundColor: _green)), if (!['sold','rejected'].contains(item.status.toLowerCase())) FilledButton.icon(onPressed: onSold, icon: const Icon(Icons.check_circle_outline), label: const Text('Mark sold'), style: FilledButton.styleFrom(backgroundColor: _green)), OutlinedButton.icon(onPressed: onDelete, icon: const Icon(Icons.delete_outline), label: const Text('Delete'), style: OutlinedButton.styleFrom(foregroundColor: Colors.red.shade700))]),
      ]),
    );
  }
}

class _Pill extends StatelessWidget {
  final String text;
  const _Pill(this.text);
  @override
  Widget build(BuildContext context) => Container(padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 6), decoration: BoxDecoration(color: const Color(0xFFF4F6F8), borderRadius: BorderRadius.circular(99)), child: Text(text, style: const TextStyle(color: _muted, fontSize: 10.5, fontWeight: FontWeight.w700)));
}

class _ErrorCard extends StatelessWidget {
  final String message;
  final VoidCallback onRetry;
  const _ErrorCard({required this.message, required this.onRetry});
  @override
  Widget build(BuildContext context) => Container(padding: const EdgeInsets.all(28), decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(12), border: Border.all(color: _border)), child: Column(children: [Icon(Icons.error_outline, size: 44, color: Colors.red.shade300), const SizedBox(height: 10), Text(message, textAlign: TextAlign.center), const SizedBox(height: 8), FilledButton(onPressed: onRetry, child: const Text('Retry'))]));
}

class _EmptyCard extends StatelessWidget {
  final VoidCallback onCreate;
  const _EmptyCard({required this.onCreate});
  @override
  Widget build(BuildContext context) => Container(padding: const EdgeInsets.symmetric(vertical: 70), decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(12), border: Border.all(color: _border)), child: Column(children: [Icon(Icons.inventory_2_outlined, size: 58, color: Colors.grey.shade300), const SizedBox(height: 8), const Text('You have no marketplace listings yet.', style: TextStyle(fontWeight: FontWeight.w900)), const SizedBox(height: 14), FilledButton.icon(onPressed: onCreate, style: FilledButton.styleFrom(backgroundColor: _green), icon: const Icon(Icons.add), label: const Text('Sell an item'))]));
}

Color _statusColor(String status) {
  switch (status.toLowerCase()) {
    case 'active': case 'approved': return _green;
    case 'pending': return Colors.orange.shade800;
    case 'reported': return Colors.red.shade700;
    case 'sold': return Colors.blueGrey;
    case 'rejected': return Colors.red.shade900;
    default: return _muted;
  }
}

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