import 'dart:async';

import 'package:flutter/material.dart';

import '../../../../core/models/user.dart';
import '../../../../core/services/campus_market_service.dart';
import '../../../../core/services/database_service.dart';
import 'active_market_sub_tab.dart';
import 'market_admin_widgets.dart';
import 'pending_market_sub_tab.dart';
import 'reported_market_sub_tab.dart';

class AdminMarketMainTab extends StatefulWidget {
  final LocalUser? currentUser;

  const AdminMarketMainTab({super.key, this.currentUser});

  @override
  State<AdminMarketMainTab> createState() => _AdminMarketMainTabState();
}

class _AdminMarketMainTabState extends State<AdminMarketMainTab> {
  int _selectedIndex = 0;
  bool _mobileMenuOpen = false;
  LocalUser? _resolvedUser;
  Timer? _countTimer;

  int _pendingCount = 0;
  int _activeCount = 0;
  int _reportedCount = 0;
  bool _loadingCounts = true;

  static const List<_AdminMarketNavItem> _navItems = <_AdminMarketNavItem>[
    _AdminMarketNavItem('Pending Approvals', Icons.pending_actions_rounded),
    _AdminMarketNavItem('Live Listings', Icons.storefront_rounded),
    _AdminMarketNavItem('Reported Items', Icons.flag_rounded),
  ];

  @override
  void initState() {
    super.initState();
    _resolvedUser = widget.currentUser;
    _resolveUser();
    _refreshCounts();
    _countTimer = Timer.periodic(const Duration(seconds: 15), (_) => _refreshCounts(silent: true));
  }

  @override
  void didUpdateWidget(covariant AdminMarketMainTab oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.currentUser != widget.currentUser) {
      _resolvedUser = widget.currentUser;
      _resolveUser();
    }
  }

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

  Future<void> _resolveUser() async {
    if (_resolvedUser != null) return;
    final user = await DatabaseService.getLocalUser();
    if (mounted && user != null) setState(() => _resolvedUser = user);
  }

  Future<void> _refreshCounts({bool silent = false}) async {
    if (!silent && mounted) setState(() => _loadingCounts = true);
    try {
      final results = await Future.wait<MarketPage>([
        CampusMarketService.getItems(status: 'pending', page: 1, limit: 1),
        CampusMarketService.getItems(status: 'active', page: 1, limit: 1),
        CampusMarketService.getItems(status: 'reported', page: 1, limit: 1),
      ]);
      if (!mounted) return;
      setState(() {
        _pendingCount = results[0].total;
        _activeCount = results[1].total;
        _reportedCount = results[2].total;
        _loadingCounts = false;
      });
    } catch (_) {
      if (mounted) setState(() => _loadingCounts = false);
    }
  }

  void _select(int index) {
    setState(() {
      _selectedIndex = index;
      _mobileMenuOpen = false;
    });
  }

  Widget _currentView() {
    switch (_selectedIndex) {
      case 0:
        return PendingMarketSubTab(onQueueChanged: _refreshCounts);
      case 1:
        return ActiveMarketSubTab(
          currentUserName: _resolvedUser?.fullName ?? 'Administrator',
          onQueueChanged: _refreshCounts,
        );
      case 2:
        return ReportedMarketSubTab(
          currentUserName: _resolvedUser?.fullName ?? 'Administrator',
          onQueueChanged: _refreshCounts,
        );
      default:
        return PendingMarketSubTab(onQueueChanged: _refreshCounts);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: marketAdminBg,
      body: LayoutBuilder(
        builder: (context, constraints) {
          final desktop = constraints.maxWidth >= 1180;
          final tablet = constraints.maxWidth >= 820 && constraints.maxWidth < 1180;

          return Stack(
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  if (desktop) SizedBox(width: 250, child: _sidebar()),
                  Expanded(
                    child: Column(
                      children: [
                        _topBar(showMenu: !desktop),
                        Expanded(
                          child: Padding(
                            padding: EdgeInsets.fromLTRB(
                              desktop ? 16 : 10,
                              12,
                              desktop || tablet ? 12 : 10,
                              0,
                            ),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Expanded(child: _currentView()),
                                if (desktop) ...[
                                  const SizedBox(width: 14),
                                  SizedBox(width: 245, child: _rightPanel()),
                                ],
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              if (!desktop && _mobileMenuOpen) ...[
                Positioned.fill(
                  child: GestureDetector(
                    onTap: () => setState(() => _mobileMenuOpen = false),
                    child: Container(color: Colors.black.withOpacity(.34)),
                  ),
                ),
                Positioned(top: 0, bottom: 0, left: 0, child: SizedBox(width: 290, child: _sidebar(mobile: true))),
              ],
            ],
          );
        },
      ),
    );
  }

  Widget _topBar({required bool showMenu}) {
    return Container(
      height: 76,
      padding: const EdgeInsets.symmetric(horizontal: 18),
      decoration: const BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(color: marketAdminBorder)),
      ),
      child: Row(
        children: [
          if (showMenu) ...[
            IconButton(
              onPressed: () => setState(() => _mobileMenuOpen = true),
              icon: const Icon(Icons.menu_rounded, color: marketAdminGreen),
            ),
            const SizedBox(width: 6),
          ],
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('Marketplace Approval Center', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w900, color: marketAdminText)),
                const SizedBox(height: 3),
                Text(
                  _selectedIndex == 0
                      ? 'Review new staff marketplace submissions'
                      : _selectedIndex == 1
                          ? 'Monitor listings currently visible to members'
                          : 'Resolve community reports and marketplace safety issues',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(color: marketAdminMuted, fontSize: 11),
                ),
              ],
            ),
          ),
          IconButton.outlined(
            onPressed: _refreshCounts,
            icon: const Icon(Icons.refresh_rounded, size: 19),
            tooltip: 'Refresh moderation counts',
          ),
          const SizedBox(width: 10),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 11, vertical: 8),
            decoration: BoxDecoration(color: marketAdminGreen.withOpacity(.06), borderRadius: BorderRadius.circular(13)),
            child: Row(
              children: [
                const CircleAvatar(
                  radius: 16,
                  backgroundColor: marketAdminGreen,
                  child: Icon(Icons.admin_panel_settings_outlined, color: Colors.white, size: 17),
                ),
                const SizedBox(width: 8),
                ConstrainedBox(
                  constraints: const BoxConstraints(maxWidth: 165),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        _resolvedUser?.fullName ?? 'Administrator',
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: const TextStyle(fontSize: 11.5, fontWeight: FontWeight.w900, color: marketAdminText),
                      ),
                      Text(
                        _resolvedUser?.campus ?? 'Rockview University',
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: const TextStyle(fontSize: 9.5, color: marketAdminMuted),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _sidebar({bool mobile = false}) {
    return Material(
      color: Colors.white,
      elevation: mobile ? 14 : 0,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            padding: const EdgeInsets.fromLTRB(20, 24, 16, 21),
            decoration: const BoxDecoration(
              color: marketAdminGreen,
              border: Border(bottom: BorderSide(color: marketAdminGold, width: 4)),
            ),
            child: Row(
              children: [
                Container(
                  width: 42,
                  height: 42,
                  decoration: BoxDecoration(color: Colors.white.withOpacity(.13), borderRadius: BorderRadius.circular(13)),
                  child: const Icon(Icons.store_mall_directory_outlined, color: Colors.white),
                ),
                const SizedBox(width: 10),
                const Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('ROCKVIEW', style: TextStyle(color: Colors.white, fontSize: 15, fontWeight: FontWeight.w900, letterSpacing: 1.1)),
                      SizedBox(height: 1),
                      Text('MARKET ADMIN', style: TextStyle(color: marketAdminGold, fontSize: 10.5, fontWeight: FontWeight.w800, letterSpacing: .8)),
                    ],
                  ),
                ),
                if (mobile)
                  IconButton(
                    onPressed: () => setState(() => _mobileMenuOpen = false),
                    icon: const Icon(Icons.close_rounded, color: Colors.white),
                  ),
              ],
            ),
          ),
          const Padding(
            padding: EdgeInsets.fromLTRB(19, 19, 19, 8),
            child: Text('MODERATION', style: TextStyle(color: marketAdminMuted, fontSize: 9.5, fontWeight: FontWeight.w900, letterSpacing: 1.1)),
          ),
          ...List.generate(_navItems.length, (index) {
            final nav = _navItems[index];
            final selected = _selectedIndex == index;
            final count = index == 0 ? _pendingCount : index == 1 ? _activeCount : _reportedCount;
            final countColor = index == 2 ? Colors.red.shade700 : index == 0 ? Colors.orange.shade800 : marketAdminGreen;
            return Padding(
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 3),
              child: InkWell(
                onTap: () => _select(index),
                borderRadius: BorderRadius.circular(13),
                child: AnimatedContainer(
                  duration: const Duration(milliseconds: 160),
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
                  decoration: BoxDecoration(
                    color: selected ? marketAdminGreen.withOpacity(.07) : Colors.transparent,
                    borderRadius: BorderRadius.circular(13),
                    border: Border.all(color: selected ? marketAdminGreen.withOpacity(.12) : Colors.transparent),
                  ),
                  child: Row(
                    children: [
                      Icon(nav.icon, color: selected ? marketAdminGreen : marketAdminMuted, size: 20),
                      const SizedBox(width: 10),
                      Expanded(
                        child: Text(nav.title, style: TextStyle(color: selected ? marketAdminText : marketAdminMuted, fontSize: 12, fontWeight: selected ? FontWeight.w900 : FontWeight.w700)),
                      ),
                      Container(
                        constraints: const BoxConstraints(minWidth: 25),
                        padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 4),
                        decoration: BoxDecoration(color: countColor.withOpacity(.09), borderRadius: BorderRadius.circular(999)),
                        child: Text(_loadingCounts ? '•' : '$count', textAlign: TextAlign.center, style: TextStyle(color: countColor, fontSize: 9.5, fontWeight: FontWeight.w900)),
                      ),
                    ],
                  ),
                ),
              ),
            );
          }),
          const Spacer(),
          Padding(
            padding: const EdgeInsets.all(15),
            child: Container(
              padding: const EdgeInsets.all(13),
              decoration: BoxDecoration(color: const Color(0xFFF7F9FA), borderRadius: BorderRadius.circular(15), border: Border.all(color: marketAdminBorder)),
              child: const Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Icon(Icons.shield_outlined, color: marketAdminGreen, size: 18),
                  SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      'Marketplace moderation actions are restricted to administrator accounts.',
                      style: TextStyle(color: marketAdminMuted, fontSize: 9.8, height: 1.45),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _rightPanel() {
    return ListView(
      padding: const EdgeInsets.only(bottom: 80),
      children: [
        _summaryCard(),
        const SizedBox(height: 12),
        Container(
          padding: const EdgeInsets.all(15),
          decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(19), border: Border.all(color: marketAdminBorder)),
          child: const Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(Icons.fact_check_outlined, color: marketAdminGreen, size: 18),
                  SizedBox(width: 7),
                  Text('Approval checklist', style: TextStyle(fontSize: 12.5, fontWeight: FontWeight.w900, color: marketAdminText)),
                ],
              ),
              SizedBox(height: 13),
              _ChecklistLine('Clear item title and description'),
              _ChecklistLine('Reasonable price and quantity'),
              _ChecklistLine('Appropriate product images'),
              _ChecklistLine('Seller and campus information'),
              _ChecklistLine('No prohibited or abusive content'),
            ],
          ),
        ),
        const SizedBox(height: 12),
        Container(
          padding: const EdgeInsets.all(15),
          decoration: BoxDecoration(color: marketAdminGold.withOpacity(.07), borderRadius: BorderRadius.circular(19), border: Border.all(color: marketAdminGold.withOpacity(.16))),
          child: const Text(
            'Approval publishes a listing immediately. Rejection keeps it out of the live marketplace while preserving the record for administrative review.',
            style: TextStyle(color: marketAdminMuted, fontSize: 10.5, height: 1.55),
          ),
        ),
      ],
    );
  }

  Widget _summaryCard() {
    return Container(
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(19), border: Border.all(color: marketAdminBorder)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text('Queue overview', style: TextStyle(fontSize: 12.5, fontWeight: FontWeight.w900, color: marketAdminText)),
          const SizedBox(height: 13),
          _SummaryRow(label: 'Pending approval', value: _pendingCount, color: Colors.orange.shade800, icon: Icons.pending_actions_rounded),
          const SizedBox(height: 9),
          _SummaryRow(label: 'Active listings', value: _activeCount, color: marketAdminGreen, icon: Icons.storefront_outlined),
          const SizedBox(height: 9),
          _SummaryRow(label: 'Reported', value: _reportedCount, color: Colors.red.shade700, icon: Icons.flag_outlined),
        ],
      ),
    );
  }
}

class _AdminMarketNavItem {
  final String title;
  final IconData icon;
  const _AdminMarketNavItem(this.title, this.icon);
}

class _SummaryRow extends StatelessWidget {
  final String label;
  final int value;
  final Color color;
  final IconData icon;

  const _SummaryRow({required this.label, required this.value, required this.color, required this.icon});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 9),
      decoration: BoxDecoration(color: color.withOpacity(.06), borderRadius: BorderRadius.circular(12)),
      child: Row(
        children: [
          Icon(icon, size: 16, color: color),
          const SizedBox(width: 7),
          Expanded(child: Text(label, style: const TextStyle(color: marketAdminMuted, fontSize: 10.5, fontWeight: FontWeight.w700))),
          Text('$value', style: TextStyle(color: color, fontSize: 14, fontWeight: FontWeight.w900)),
        ],
      ),
    );
  }
}

class _ChecklistLine extends StatelessWidget {
  final String text;
  const _ChecklistLine(this.text);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Icon(Icons.check_circle_outline_rounded, size: 14, color: marketAdminGreen),
          const SizedBox(width: 7),
          Expanded(child: Text(text, style: const TextStyle(color: marketAdminMuted, fontSize: 10.2, height: 1.35))),
        ],
      ),
    );
  }
}
