import 'package:flutter/material.dart';

import '../../../../core/models/user.dart';
import '../../../../core/services/market_offline_service.dart';
import '../../../../core/services/database_service.dart';
import 'active_market_sub_tab.dart';
import 'my_market_sub_tab.dart';
import 'reported_market_sub_tab.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 StaffMarketMainTab extends StatefulWidget {
  final LocalUser? currentUser;

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

  @override
  State<StaffMarketMainTab> createState() => _StaffMarketMainTabState();
}

class _StaffMarketMainTabState extends State<StaffMarketMainTab> with WidgetsBindingObserver {
  int _selected = 0;
  bool _drawerOpen = false;
  LocalUser? _resolvedUser;
  bool _isAdmin = false;
  final Set<int> _visited={0};
  bool _userLoading=false;

  @override
  void initState() {
    super.initState();
    _resolvedUser = widget.currentUser;
    WidgetsBinding.instance.addObserver(this);
    MarketOfflineService.revision.addListener(_loadUser);
    MarketOfflineService.start().then((_)=>_loadUser()).catchError((Object e){if(mounted)setState(()=>_isAdmin=false);});
    _loadUser();
  }

  Future<void> _loadUser() async {
    if(_userLoading)return;_userLoading=true;
    try {
      final local = await DatabaseService.getLocalUser();
      if(mounted)setState(()=>_resolvedUser=local);
      final me = await MarketOfflineService.getCurrentUser(requireFreshRole:true);
      if (!mounted) return;
      final role = '${me['role'] ?? ''}'.trim().toLowerCase();
      setState((){_isAdmin=<String>{'admin','administrator','superadmin','super_admin'}.contains(role);if(!_isAdmin&&_selected==2)_selected=0;});
    } catch (_) {if(mounted)setState((){_isAdmin=false;if(_selected==2)_selected=0;});}
    finally{_userLoading=false;}
  }

  List<_MenuItem> get _menu => <_MenuItem>[
        const _MenuItem('Marketplace', 'Browse active staff listings', Icons.storefront_rounded),
        const _MenuItem('My Listings', 'Manage items you are selling', Icons.inventory_2_outlined),
        if (_isAdmin) const _MenuItem('Moderation', 'Approve and review listings', Icons.admin_panel_settings_outlined),
      ];

  Widget _viewFor(int index) {
    final name = _resolvedUser?.fullName ?? 'Rockview Member';
    if (index == 1) return const MyMarketSubTab(key: ValueKey('my-market'));
    if (index == 2 && _isAdmin) return ReportedMarketSubTab(key: const ValueKey('market-moderation'), currentUserName: name);
    return ActiveMarketSubTab(key: const ValueKey('active-market'), currentUserName: name);
  }

  void _select(int index) {
    setState(() {
      _selected = index;
      _visited.add(index);
      _drawerOpen = false;
    });
  }

  @override void didChangeAppLifecycleState(AppLifecycleState state){
    final active=state==AppLifecycleState.resumed;MarketOfflineService.setForeground(active);
    if(active)MarketOfflineService.sync();
  }
  @override void dispose(){
    WidgetsBinding.instance.removeObserver(this);MarketOfflineService.revision.removeListener(_loadUser);MarketOfflineService.stop();super.dispose();
  }
  Widget _keptViews()=>ValueListenableBuilder<String>(valueListenable:MarketOfflineService.accountScope,
    builder:(context,scope,_)=>scope.isEmpty?const Center(child:Text('Sign in or reconnect to open your saved marketplace.')):
      IndexedStack(key:ValueKey(scope),index:_selected,children:[
        for(var i=0;i<3;i++)_visited.contains(i)&&(i!=2||_isAdmin)?TickerMode(enabled:_selected==i,child:_viewFor(i)):const SizedBox.shrink(),
      ]));
  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final desktop = constraints.maxWidth >= 1180;
        final tablet = constraints.maxWidth >= 850;
        return Scaffold(
          backgroundColor: const Color(0xFFF3F5F7),
          body: Stack(
            children: [
              SafeArea(
                child: Column(
                  children: [
                    _Header(onMenu: desktop ? null : () => setState(() => _drawerOpen = true)),
                    Expanded(
                      child: Row(
                        children: [
                          if (desktop) SizedBox(width: 220, child: _LeftPanel(items: _menu, selected: _selected, onSelect: _select)),
                          Expanded(
                            child: Padding(
                              padding: EdgeInsets.fromLTRB(desktop ? 18 : 12, 12, desktop ? 18 : 12, 12),
                              child: Center(
                                child: ConstrainedBox(
                                  constraints: BoxConstraints(maxWidth: desktop ? 1480 : (tablet ? 1100 : 850)),
                                  child: Row(
                                    crossAxisAlignment: CrossAxisAlignment.stretch,
                                    children: [
                                      Expanded(child: _keptViews()),
                                      
                                      
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              if (!desktop && _drawerOpen) ...[
                Positioned.fill(child: GestureDetector(onTap: () => setState(() => _drawerOpen = false), child: Container(color: Colors.black.withOpacity(0.28)))),
                Positioned(top: 0, bottom: 0, left: 0, child: SafeArea(child: SizedBox(width: 290, child: _LeftPanel(items: _menu, selected: _selected, onSelect: _select)))),
              ],
            ],
          ),
        );
      },
    );
  }
}

class _Header extends StatelessWidget {
  final VoidCallback? onMenu;
  const _Header({this.onMenu});

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.fromLTRB(12, 12, 12, 0),
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(14), border: Border.all(color: _border)),
      child: Row(children: [
        if (onMenu != null) ...[IconButton(onPressed: onMenu, icon: const Icon(Icons.menu_rounded, color: _green)), const SizedBox(width: 6)],
        Container(width: 42, height: 42, decoration: BoxDecoration(color: _green.withOpacity(0.08), borderRadius: BorderRadius.circular(13)), child: const Icon(Icons.store_mall_directory_rounded, color: _green)),
        const SizedBox(width: 11),
        const Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text('Rockview Staff Marketplace', style: TextStyle(fontSize: 17, fontWeight: FontWeight.w900, color: Color(0xFF173029))), SizedBox(height: 3), Text('A professional internal marketplace for staff and university members.', maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 11.5, color: _muted, fontWeight: FontWeight.w600))])),
        Container(padding: const EdgeInsets.symmetric(horizontal: 11, vertical: 7), decoration: BoxDecoration(color: _gold.withOpacity(0.10), borderRadius: BorderRadius.circular(99)), child: const Row(mainAxisSize: MainAxisSize.min, children: [Icon(Icons.verified_user_outlined, color: _gold, size: 15), SizedBox(width: 5), Text('Members only', style: TextStyle(color: Color(0xFF785321), fontSize: 10.5, fontWeight: FontWeight.w800))])),
      ]),
    );
  }
}

class _LeftPanel extends StatelessWidget {
  final List<_MenuItem> items;
  final int selected;
  final ValueChanged<int> onSelect;

  const _LeftPanel({required this.items, required this.selected, required this.onSelect});

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.fromLTRB(12, 12, 0, 12),
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(26), border: Border.all(color: _border)),
      child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
        Container(padding: const EdgeInsets.all(17), decoration: BoxDecoration(gradient: LinearGradient(colors: [_green, _green.withOpacity(0.86)]), borderRadius: BorderRadius.circular(20)), child: const Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text('Marketplace', style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.w900)), SizedBox(height: 7), Text('Sell useful goods to colleagues, discover listings and communicate safely inside Rockview.', style: TextStyle(color: Colors.white70, fontSize: 11.5, height: 1.5))])),
        const SizedBox(height: 14),
        for (var i = 0; i < items.length; i++) Padding(padding: const EdgeInsets.only(bottom: 9), child: _NavItem(item: items[i], active: selected == i, onTap: () => onSelect(i))),
        const Spacer(),
        Container(padding: const EdgeInsets.all(14), decoration: BoxDecoration(color: const Color(0xFFF7F9FA), borderRadius: BorderRadius.circular(17)), child: const Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text('Marketplace safety', style: TextStyle(fontWeight: FontWeight.w900, fontSize: 11.5)), SizedBox(height: 8), _Bullet('Describe goods accurately.'), _Bullet('Use university-safe pickup locations.'), _Bullet('Report suspicious listings.'), _Bullet('Mark sold items promptly.')]))
      ]),
    );
  }
}

class _NavItem extends StatelessWidget {
  final _MenuItem item;
  final bool active;
  final VoidCallback onTap;
  const _NavItem({required this.item, required this.active, required this.onTap});

  @override
  Widget build(BuildContext context) => InkWell(onTap: onTap, borderRadius: BorderRadius.circular(16), child: Container(padding: const EdgeInsets.all(12), decoration: BoxDecoration(color: active ? _green.withOpacity(0.07) : const Color(0xFFF8FAFB), borderRadius: BorderRadius.circular(16), border: Border.all(color: active ? _green.withOpacity(0.16) : _border)), child: Row(children: [Container(width: 37, height: 37, decoration: BoxDecoration(color: active ? _green : Colors.white, borderRadius: BorderRadius.circular(11)), child: Icon(item.icon, color: active ? Colors.white : _muted, size: 20)), const SizedBox(width: 10), Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text(item.title, style: TextStyle(fontWeight: FontWeight.w900, color: active ? _green : const Color(0xFF1F2D3A))), const SizedBox(height: 3), Text(item.subtitle, style: const TextStyle(fontSize: 10.5, color: _muted))]))])));
}

class _RightPanel extends StatelessWidget {
  const _RightPanel();
  @override
  Widget build(BuildContext context) => Container(margin: const EdgeInsets.fromLTRB(0, 0, 0, 0), child: const Column(children: [_InfoCard(icon: Icons.photo_library_outlined, title: 'Compact media', body: 'Listings can contain up to six pictures. Cards show one lead image with +N for the remaining photos.'), SizedBox(height: 12), _InfoCard(icon: Icons.forum_outlined, title: 'Buyer & seller discussion', body: 'Members can like, comment, reply, mention colleagues and send an interest message to the seller.'), SizedBox(height: 12), _InfoCard(icon: Icons.update_rounded, title: 'Dynamic marketplace', body: 'Newest approved listings appear first and the active feed checks quietly for fresh items.') ]));
}

class _InfoCard extends StatelessWidget {
  final IconData icon;
  final String title;
  final String body;
  const _InfoCard({required this.icon, required this.title, required this.body});
  @override
  Widget build(BuildContext context) => Container(width: double.infinity, padding: const EdgeInsets.all(15), decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(20), border: Border.all(color: _border)), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Container(width: 39, height: 39, decoration: BoxDecoration(color: _gold.withOpacity(0.1), borderRadius: BorderRadius.circular(12)), child: Icon(icon, color: _gold, size: 20)), const SizedBox(height: 10), Text(title, style: const TextStyle(fontWeight: FontWeight.w900, fontSize: 12.5)), const SizedBox(height: 6), Text(body, style: const TextStyle(color: _muted, fontSize: 11, height: 1.5))]));
}

class _Bullet extends StatelessWidget {
  final String text;
  const _Bullet(this.text);
  @override
  Widget build(BuildContext context) => Padding(padding: const EdgeInsets.only(bottom: 6), child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [Container(width: 6, height: 6, margin: const EdgeInsets.only(top: 5), decoration: const BoxDecoration(color: _gold, shape: BoxShape.circle)), const SizedBox(width: 7), Expanded(child: Text(text, style: const TextStyle(fontSize: 10.5, color: _muted))) ]));
}

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