import 'dart:async';

import 'package:flutter/material.dart';

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

class PendingMarketSubTab extends StatefulWidget {
  final VoidCallback? onQueueChanged;

  const PendingMarketSubTab({super.key, this.onQueueChanged});

  @override
  State<PendingMarketSubTab> createState() => _PendingMarketSubTabState();
}

class _PendingMarketSubTabState extends State<PendingMarketSubTab> {
  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: 15), (_) => _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: 'pending',
          campus: _campus,
          category: _category,
          search: _searchController.text,
          limit: 50,
        ),
      ]);
      if (!mounted) return;
      final page = results[1] as MarketPage;
      setState(() {
        _campuses = List<String>.from(results[0] as List);
        _items = page.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: 'pending',
        campus: _campus,
        category: _category,
        search: _searchController.text,
        limit: 50,
      );
      if (!mounted) return;
      setState(() => _items = page.items);
      widget.onQueueChanged?.call();
    } catch (_) {}
  }

  Future<void> _approve(MarketItem item) async {
    try {
      await CampusMarketService.moderateItem(item.id, 'approve');
      if (!mounted) return;
      setState(() => _items.removeWhere((row) => row.id == item.id));
      widget.onQueueChanged?.call();
      _snack('"${item.title}" approved and published.', marketAdminGreen);
    } catch (e) {
      _snack(marketAdminCleanError(e), Colors.red.shade700);
    }
  }

  Future<void> _reject(MarketItem item) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (_) => AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
        title: const Text('Reject listing?'),
        content: Text('"${item.title}" will not appear in the marketplace. The listing record will be retained 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('Reject'),
          ),
        ],
      ),
    );
    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 rejected.', Colors.red.shade700);
    } 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: 'Reject', icon: Icons.close_rounded, color: Colors.red.shade700, filled: false, onPressed: () {
            Navigator.pop(context);
            _reject(item);
          }),
          marketAdminActionButton(label: 'Approve & Publish', icon: Icons.check_circle_outline_rounded, onPressed: () {
            Navigator.pop(context);
            _approve(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.verified_outlined,
              title: 'Approval queue is clear',
              message: 'There are no staff marketplace listings waiting for approval.',
              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: 'Pending approval',
                      statusColor: Colors.orange.shade800,
                      onOpen: () => _open(item),
                      footer: Row(
                        children: [
                          Expanded(
                            child: marketAdminActionButton(
                              label: 'Reject',
                              icon: Icons.close_rounded,
                              color: Colors.red.shade700,
                              filled: false,
                              onPressed: () => _reject(item),
                            ),
                          ),
                          const SizedBox(width: 8),
                          Expanded(
                            child: marketAdminActionButton(
                              label: 'Approve',
                              icon: Icons.check_circle_outline_rounded,
                              onPressed: () => _approve(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: Colors.orange.withOpacity(.09), borderRadius: BorderRadius.circular(15)),
            child: Icon(Icons.pending_actions_rounded, color: Colors.orange.shade800),
          ),
          const SizedBox(width: 12),
          const Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('Pending Approvals', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w900, color: marketAdminText)),
                SizedBox(height: 4),
                Text('Review staff submissions before they become visible in the marketplace.', style: TextStyle(color: marketAdminMuted, fontSize: 11.5)),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            decoration: BoxDecoration(color: Colors.orange.shade50, borderRadius: BorderRadius.circular(999)),
            child: Text('${_items.length} WAITING', style: TextStyle(color: Colors.orange.shade800, fontSize: 10, fontWeight: FontWeight.w900)),
          ),
        ],
      ),
    );
  }
}
