import 'dart:async';

import 'package:flutter/material.dart';

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

class ActiveMarketSubTab extends StatefulWidget {
  final String currentUserName;
  final VoidCallback? onQueueChanged;

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

  @override
  State<ActiveMarketSubTab> createState() => _ActiveMarketSubTabState();
}

class _ActiveMarketSubTabState extends State<ActiveMarketSubTab> {
  final TextEditingController _searchController = TextEditingController();
  List<MarketItem> _items = <MarketItem>[];
  List<String> _campuses = <String>[];
  String _campus = 'All Campuses';
  String _category = 'All Categories';
  bool _loading = true;
  String? _error;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _load();
    _timer = Timer.periodic(const Duration(seconds: 20), (_) => _silentRefresh());
  }

  @override
  void dispose() {
    _timer?.cancel();
    _searchController.dispose();
    super.dispose();
  }

  Future<void> _load() async {
    if (!mounted) return;
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final results = await Future.wait<dynamic>([
        CampusMarketService.getCampuses(),
        CampusMarketService.getItems(
          status: 'active',
          campus: _campus,
          category: _category,
          search: _searchController.text,
          limit: 50,
        ),
      ]);
      if (!mounted) return;
      setState(() {
        _campuses = List<String>.from(results[0] as List);
        _items = (results[1] as MarketPage).items;
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loading = false;
        _error = marketAdminCleanError(e);
      });
    }
  }

  Future<void> _silentRefresh() async {
    if (_loading) return;
    try {
      final page = await CampusMarketService.getItems(
        status: 'active',
        campus: _campus,
        category: _category,
        search: _searchController.text,
        limit: 50,
      );
      if (mounted) setState(() => _items = page.items);
    } catch (_) {}
  }

  Future<void> _remove(MarketItem item) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (_) => AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
        title: const Text('Remove from marketplace?'),
        content: Text('"${item.title}" will be removed from the active marketplace and retained as rejected for audit purposes.'),
        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('Remove'),
          ),
        ],
      ),
    );
    if (confirmed != true) return;
    try {
      await CampusMarketService.moderateItem(item.id, 'reject');
      if (!mounted) return;
      setState(() => _items.removeWhere((row) => row.id == item.id));
      widget.onQueueChanged?.call();
      _snack('Listing removed from the active marketplace.', Colors.red.shade700);
    } catch (e) {
      _snack(marketAdminCleanError(e), Colors.red.shade700);
    }
  }

  Future<void> _deletePermanently(MarketItem item) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (_) => AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
        title: const Text('Delete permanently?'),
        content: Text('This permanently deletes "${item.title}" and its uploaded images. This action cannot be undone.'),
        actions: [
          TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Cancel')),
          FilledButton(
            onPressed: () => Navigator.pop(context, true),
            style: FilledButton.styleFrom(backgroundColor: Colors.red.shade900),
            child: const Text('Delete Permanently'),
          ),
        ],
      ),
    );
    if (confirmed != true) return;
    try {
      await CampusMarketService.deleteItem(item.id);
      if (!mounted) return;
      setState(() => _items.removeWhere((row) => row.id == item.id));
      widget.onQueueChanged?.call();
      _snack('Listing permanently deleted.', Colors.black87);
    } catch (e) {
      _snack(marketAdminCleanError(e), Colors.red.shade700);
    }
  }

  void _open(MarketItem item) {
    showMarketAdminDetails(
      context,
      item,
      actions: Wrap(
        alignment: WrapAlignment.end,
        spacing: 8,
        runSpacing: 8,
        children: [
          marketAdminActionButton(
            label: 'Delete permanently',
            icon: Icons.delete_forever_outlined,
            color: Colors.red.shade900,
            filled: false,
            onPressed: () {
              Navigator.pop(context);
              _deletePermanently(item);
            },
          ),
          marketAdminActionButton(
            label: 'Remove from market',
            icon: Icons.block_outlined,
            color: Colors.red.shade700,
            onPressed: () {
              Navigator.pop(context);
              _remove(item);
            },
          ),
        ],
      ),
    );
  }

  void _snack(String message, Color color) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message), backgroundColor: color, behavior: SnackBarBehavior.floating));
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: _load,
      color: marketAdminGreen,
      child: ListView(
        physics: const AlwaysScrollableScrollPhysics(),
        padding: const EdgeInsets.fromLTRB(0, 4, 0, 90),
        children: [
          _header(),
          const SizedBox(height: 12),
          MarketAdminFilters(
            searchController: _searchController,
            campuses: _campuses,
            campus: _campus,
            category: _category,
            onCampusChanged: (value) {
              setState(() => _campus = value);
              _load();
            },
            onCategoryChanged: (value) {
              setState(() => _category = value);
              _load();
            },
            onSearch: _load,
            onRefresh: _load,
          ),
          const SizedBox(height: 14),
          if (_loading)
            const Padding(padding: EdgeInsets.symmetric(vertical: 100), child: Center(child: CircularProgressIndicator(color: marketAdminGreen)))
          else if (_error != null)
            MarketAdminErrorState(message: _error!, onRetry: _load)
          else if (_items.isEmpty)
            MarketAdminEmptyState(
              icon: Icons.storefront_outlined,
              title: 'No active listings',
              message: 'Approved marketplace items will appear here.',
              onRefresh: _load,
            )
          else
            LayoutBuilder(
              builder: (context, constraints) {
                final columns = constraints.maxWidth >= 1080 ? 3 : constraints.maxWidth >= 650 ? 2 : 1;
                final width = (constraints.maxWidth - ((columns - 1) * 12)) / columns;
                return Wrap(
                  spacing: 12,
                  runSpacing: 12,
                  children: _items.map((item) => SizedBox(
                    width: width,
                    child: MarketAdminItemCard(
                      item: item,
                      statusLabel: 'Active',
                      statusColor: marketAdminGreen,
                      onOpen: () => _open(item),
                      footer: Row(
                        children: [
                          Expanded(
                            child: marketAdminActionButton(
                              label: 'View',
                              icon: Icons.visibility_outlined,
                              filled: false,
                              onPressed: () => _open(item),
                            ),
                          ),
                          const SizedBox(width: 8),
                          Expanded(
                            child: marketAdminActionButton(
                              label: 'Remove',
                              icon: Icons.block_outlined,
                              color: Colors.red.shade700,
                              onPressed: () => _remove(item),
                            ),
                          ),
                        ],
                      ),
                    ),
                  )).toList(),
                );
              },
            ),
        ],
      ),
    );
  }

  Widget _header() {
    return Container(
      padding: const EdgeInsets.all(17),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(20), border: Border.all(color: marketAdminBorder)),
      child: Row(
        children: [
          Container(
            width: 48,
            height: 48,
            decoration: BoxDecoration(color: marketAdminGreen.withOpacity(.07), borderRadius: BorderRadius.circular(15)),
            child: const Icon(Icons.storefront_rounded, color: marketAdminGreen),
          ),
          const SizedBox(width: 12),
          const Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('Live Marketplace', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w900, color: marketAdminText)),
                SizedBox(height: 4),
                Text('Review the listings currently visible to Rockview members.', style: TextStyle(color: marketAdminMuted, fontSize: 11.5)),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            decoration: BoxDecoration(color: marketAdminGreen.withOpacity(.08), borderRadius: BorderRadius.circular(999)),
            child: Text('${_items.length} ACTIVE', style: const TextStyle(color: marketAdminGreen, fontSize: 10, fontWeight: FontWeight.w900)),
          ),
        ],
      ),
    );
  }
}
