import 'package:flutter/material.dart';

import '../../../../core/models/user.dart';
import '../../../../core/services/database_service.dart';
import 'pending_qa_sub_tab.dart';
import 'resolved_qa_sub_tab.dart';

const Color _qaGreen = Color.fromARGB(255, 2, 105, 48);
const Color _qaGold = Color.fromARGB(255, 204, 117, 4);
const Color _qaBg = Color(0xFFF3F6F5);
const Color _qaBorder = Color(0xFFE1E7E4);
const Color _qaMuted = Color(0xFF66736D);

class StaffQaMainTab extends StatefulWidget {
  final LocalUser? currentUser;

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

  @override
  State<StaffQaMainTab> createState() => _StaffQaMainTabState();
}

class _StaffQaMainTabState extends State<StaffQaMainTab> {
  int _currentIndex = 0;
  LocalUser? _resolvedUser;

  @override
  void initState() {
    super.initState();
    _resolvedUser = widget.currentUser;
    _loadUser();
  }

  Future<void> _loadUser() async {
    if (_resolvedUser != null) return;
    try {
      final user = await DatabaseService.getLocalUser();
      if (!mounted || user == null) return;
      setState(() => _resolvedUser = user);
    } catch (_) {}
  }

  String get _staffName => _resolvedUser?.fullName ?? 'Staff Member';

  Widget _currentView() {
    if (_currentIndex == 1) {
      return ResolvedQaSubTab(
        key: const ValueKey('resolved-support'),
        currentUserName: _staffName,
      );
    }
    return PendingQaSubTab(
      key: const ValueKey('open-support'),
      currentUserName: _staffName,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: _qaBg,
      body: LayoutBuilder(
        builder: (context, constraints) {
          final desktop = constraints.maxWidth >= 980;
          if (desktop) {
            return Row(
              children: [
                _desktopNavigation(),
                Expanded(child: _currentView()),
              ],
            );
          }
          return Column(
            children: [
              _mobileHeader(),
              Expanded(child: _currentView()),
            ],
          );
        },
      ),
    );
  }

  Widget _desktopNavigation() {
    return Container(
      width: 252,
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            padding: const EdgeInsets.fromLTRB(22, 26, 22, 22),
            decoration: const BoxDecoration(
              border: Border(bottom: BorderSide(color: _qaBorder)),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Container(
                      width: 42,
                      height: 42,
                      decoration: BoxDecoration(
                        color: _qaGreen,
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: const Icon(Icons.support_agent_rounded, color: Colors.white),
                    ),
                    const SizedBox(width: 10),
                    const Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            'STAFF SUPPORT',
                            style: TextStyle(
                              color: _qaGreen,
                              fontSize: 15,
                              fontWeight: FontWeight.w900,
                              letterSpacing: .7,
                            ),
                          ),
                          SizedBox(height: 2),
                          Text(
                            'Q&A Conversations',
                            style: TextStyle(fontSize: 10.5, color: _qaMuted),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 18),
                Text(
                  _staffName,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(fontWeight: FontWeight.w900, fontSize: 13),
                ),
                const SizedBox(height: 3),
                Text(
                  _resolvedUser?.campus?.toString().trim().isNotEmpty == true
                      ? _resolvedUser!.campus.toString()
                      : 'Rockview University',
                  style: const TextStyle(fontSize: 10.5, color: _qaMuted),
                ),
              ],
            ),
          ),
          const SizedBox(height: 14),
          _navItem(
            index: 0,
            icon: Icons.forum_outlined,
            selectedIcon: Icons.forum_rounded,
            title: 'Open Conversations',
            subtitle: 'Questions and replies',
          ),
          _navItem(
            index: 1,
            icon: Icons.task_alt_outlined,
            selectedIcon: Icons.task_alt_rounded,
            title: 'Resolved',
            subtitle: 'Completed support',
          ),
          const Spacer(),
          Container(
            margin: const EdgeInsets.all(16),
            padding: const EdgeInsets.all(14),
            decoration: BoxDecoration(
              color: _qaGreen.withOpacity(.045),
              borderRadius: BorderRadius.circular(15),
              border: Border.all(color: _qaGreen.withOpacity(.12)),
            ),
            child: const Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Icon(Icons.lock_outline_rounded, size: 16, color: _qaGreen),
                    SizedBox(width: 6),
                    Text('PRIVATE SUPPORT', style: TextStyle(fontSize: 9.5, fontWeight: FontWeight.w900, color: _qaGreen)),
                  ],
                ),
                SizedBox(height: 7),
                Text(
                  'Your support conversations are visible to you and authorized administrators.',
                  style: TextStyle(fontSize: 10.5, color: _qaMuted, height: 1.45),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _navItem({
    required int index,
    required IconData icon,
    required IconData selectedIcon,
    required String title,
    required String subtitle,
  }) {
    final selected = _currentIndex == index;
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
      child: Material(
        color: selected ? _qaGreen.withOpacity(.07) : Colors.transparent,
        borderRadius: BorderRadius.circular(14),
        child: InkWell(
          onTap: () => setState(() => _currentIndex = index),
          borderRadius: BorderRadius.circular(14),
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 13, vertical: 13),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(14),
              border: Border(
                left: BorderSide(
                  color: selected ? _qaGold : Colors.transparent,
                  width: 3,
                ),
              ),
            ),
            child: Row(
              children: [
                Icon(selected ? selectedIcon : icon, color: selected ? _qaGreen : Colors.grey.shade500, size: 21),
                const SizedBox(width: 11),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        title,
                        style: TextStyle(
                          fontSize: 12.5,
                          fontWeight: selected ? FontWeight.w900 : FontWeight.w700,
                          color: selected ? _qaGreen : const Color(0xFF37463F),
                        ),
                      ),
                      const SizedBox(height: 2),
                      Text(subtitle, style: const TextStyle(fontSize: 9.5, color: _qaMuted)),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _mobileHeader() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.fromLTRB(12, 10, 12, 8),
      child: Row(
        children: [
          Expanded(
            child: SegmentedButton<int>(
              segments: const [
                ButtonSegment(value: 0, icon: Icon(Icons.forum_rounded, size: 17), label: Text('Open')),
                ButtonSegment(value: 1, icon: Icon(Icons.task_alt_rounded, size: 17), label: Text('Resolved')),
              ],
              selected: <int>{_currentIndex},
              onSelectionChanged: (value) => setState(() => _currentIndex = value.first),
              style: ButtonStyle(
                visualDensity: VisualDensity.compact,
                foregroundColor: MaterialStateProperty.resolveWith(
                  (states) => states.contains(MaterialState.selected) ? _qaGreen : _qaMuted,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
