// lib/features/admin/tabs/staff_lectures/active_lectures_sub_tab.dart

import 'dart:convert';
import 'dart:typed_data';

import 'package:flutter/material.dart';

import '../../../../core/networks/api_client.dart';

const Color _standardGold = Color.fromARGB(255, 204, 117, 4);
const Color _darkGreen = Color.fromARGB(255, 2, 105, 48);
const Color _ink = Color(0xFF24332B);

class ActiveLecturesSubTab extends StatefulWidget {
  const ActiveLecturesSubTab({super.key});

  @override
  State<ActiveLecturesSubTab> createState() => _ActiveLecturesSubTabState();
}

class _ActiveLecturesSubTabState extends State<ActiveLecturesSubTab> {
  final TextEditingController _searchController = TextEditingController();
  List<Map<String, dynamic>> _staff = [];
  bool _loading = true;
  String? _error;
  String _campusFilter = 'All Campuses';

  @override
  void initState() {
    super.initState();
    _loadStaff();
  }

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

  Future<void> _loadStaff() async {
    if (!mounted) return;
    setState(() {
      _loading = true;
      _error = null;
    });

    try {
      final result = await ApiClient.getStaff();
      final clean = <Map<String, dynamic>>[];
      for (final row in result) {
        clean.add(row.map((key, value) => MapEntry(key.toString(), value)));
      }
      clean.sort((a, b) => _staffName(a).toLowerCase().compareTo(_staffName(b).toLowerCase()));
      if (!mounted) return;
      setState(() => _staff = clean);
    } catch (e) {
      if (!mounted) return;
      setState(() => _error = e.toString());
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  String _text(dynamic value, [String fallback = '']) {
    final result = value?.toString().trim() ?? '';
    return result.isEmpty || result.toLowerCase() == 'null' ? fallback : result;
  }

  String _staffName(Map<String, dynamic> staff) =>
      _text(staff['full_name'], _text(staff['name'], 'Unnamed Staff'));

  String _staffCampus(Map<String, dynamic> staff) =>
      _text(staff['campus'], 'Campus not assigned');

  String _staffSchool(Map<String, dynamic> staff) =>
      _text(staff['school'], 'School not assigned');

  String _staffDepartment(Map<String, dynamic> staff) => _text(
        staff['department'],
        _text(staff['program'], 'Department not assigned'),
      );

  List<String> get _campuses {
    final values = _staff
        .map(_staffCampus)
        .where((campus) => campus != 'Campus not assigned')
        .toSet()
        .toList()
      ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
    return ['All Campuses', ...values];
  }

  List<Map<String, dynamic>> get _visibleStaff {
    final query = _searchController.text.trim().toLowerCase();
    return _staff.where((staff) {
      final campusMatches = _campusFilter == 'All Campuses' ||
          _staffCampus(staff) == _campusFilter;
      if (!campusMatches) return false;
      if (query.isEmpty) return true;

      final haystack = [
        _staffName(staff),
        _text(staff['email']),
        _text(staff['phone']),
        _staffCampus(staff),
        _staffSchool(staff),
        _staffDepartment(staff),
      ].join(' ').toLowerCase();
      return haystack.contains(query);
    }).toList();
  }

  int get _campusCount => _staff
      .map(_staffCampus)
      .where((value) => value != 'Campus not assigned')
      .toSet()
      .length;

  int get _schoolCount => _staff
      .map(_staffSchool)
      .where((value) => value != 'School not assigned')
      .toSet()
      .length;

  void _showStaffDetails(Map<String, dynamic> staff) {
    showDialog<void>(
      context: context,
      builder: (context) => Dialog(
        shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
        backgroundColor: Colors.white,
        child: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 560),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 20),
                decoration: const BoxDecoration(
                  color: _darkGreen,
                  border: Border(bottom: BorderSide(color: _standardGold, width: 3)),
                ),
                child: Row(
                  children: [
                    const Icon(Icons.badge_outlined, color: Colors.white),
                    const SizedBox(width: 12),
                    Expanded(
                      child: Text(
                        _staffName(staff).toUpperCase(),
                        style: const TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.w900,
                          letterSpacing: 1,
                        ),
                      ),
                    ),
                    IconButton(
                      onPressed: () => Navigator.pop(context),
                      icon: const Icon(Icons.close, color: Colors.white),
                    ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(28),
                child: Column(
                  children: [
                    SizedBox(
                      width: 110,
                      height: 110,
                      child: ClipOval(child: _profileImage(staff['profile_picture'])),
                    ),
                    const SizedBox(height: 24),
                    _detailRow(Icons.domain_outlined, 'Campus', _staffCampus(staff)),
                    _detailRow(Icons.account_balance_outlined, 'School', _staffSchool(staff)),
                    _detailRow(Icons.account_tree_outlined, 'Department', _staffDepartment(staff)),
                    _detailRow(Icons.email_outlined, 'Email', _text(staff['email'], 'Not provided')),
                    _detailRow(Icons.phone_outlined, 'Phone', _text(staff['phone'], 'Not provided')),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _detailRow(IconData icon, String label, String value) {
    return Container(
      margin: const EdgeInsets.only(bottom: 10),
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: const Color(0xFFF8FAF8),
        border: Border.all(color: const Color(0xFFE1E8E3)),
      ),
      child: Row(
        children: [
          Icon(icon, size: 20, color: _darkGreen),
          const SizedBox(width: 12),
          SizedBox(
            width: 92,
            child: Text(label, style: const TextStyle(fontWeight: FontWeight.w700, color: _ink)),
          ),
          Expanded(child: Text(value, style: const TextStyle(color: Color(0xFF607067)))),
        ],
      ),
    );
  }

  String? _profileUrl(String value) {
    final raw = value.trim();
    if (raw.isEmpty) return null;
    if (raw.startsWith('http://') || raw.startsWith('https://')) return raw;
    if (raw.startsWith('uploads/') || raw.startsWith('/uploads/')) {
      final relative = raw.startsWith('/') ? raw.substring(1) : raw;
      final base = ApiClient.baseUrl.endsWith('/')
          ? ApiClient.baseUrl.substring(0, ApiClient.baseUrl.length - 1)
          : ApiClient.baseUrl;
      return '$base/$relative';
    }
    return null;
  }

  Uint8List? _legacyBase64Bytes(String raw) {
    try {
      final source = raw.contains(',') && raw.startsWith('data:image')
          ? raw.substring(raw.indexOf(',') + 1)
          : raw;
      return base64Decode(source);
    } catch (_) {
      return null;
    }
  }

  Widget _profileImage(dynamic rawValue) {
    final raw = _text(rawValue);
    if (raw.isEmpty) return _profileFallback();

    final url = _profileUrl(raw);
    if (url != null) {
      return Image.network(
        url,
        fit: BoxFit.cover,
        errorBuilder: (_, __, ___) => _profileFallback(),
      );
    }

    final bytes = _legacyBase64Bytes(raw);
    if (bytes != null) {
      return Image.memory(
        bytes,
        fit: BoxFit.cover,
        errorBuilder: (_, __, ___) => _profileFallback(),
      );
    }

    return _profileFallback();
  }

  Widget _profileFallback() => Container(
        color: const Color(0xFFEFF3F0),
        alignment: Alignment.center,
        child: const Icon(Icons.person_rounded, size: 44, color: Color(0xFF8D9B92)),
      );

  @override
  Widget build(BuildContext context) {
    return Material(
      color: const Color(0xFFF4F6F5),
      child: LayoutBuilder(
        builder: (context, constraints) {
          final width = constraints.maxWidth;
          final horizontalPadding = width < 700 ? 14.0 : 28.0;

          return Padding(
            padding: EdgeInsets.fromLTRB(horizontalPadding, 0, horizontalPadding, 24),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                _buildHero(width),
                const SizedBox(height: 18),
                _buildToolbar(width),
                const SizedBox(height: 18),
                Expanded(child: _buildContent(width)),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildHero(double width) {
    final compact = width < 760;
    final stats = [
      _StatData(Icons.people_alt_outlined, '${_staff.length}', 'Staff Members'),
      _StatData(Icons.domain_outlined, '$_campusCount', 'Campuses'),
      _StatData(Icons.account_balance_outlined, '$_schoolCount', 'Schools'),
    ];

    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: const Color(0xFFDCE3DE)),
        boxShadow: const [
          BoxShadow(color: Color(0x11000000), blurRadius: 16, offset: Offset(0, 6)),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(height: 4, color: _standardGold),
          Padding(
            padding: EdgeInsets.all(compact ? 20 : 28),
            child: compact
                ? Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _heroCopy(),
                      const SizedBox(height: 20),
                      Wrap(spacing: 10, runSpacing: 10, children: stats.map(_statBox).toList()),
                    ],
                  )
                : Row(
                    children: [
                      Expanded(child: _heroCopy()),
                      const SizedBox(width: 24),
                      ...stats.map((item) => Padding(
                            padding: const EdgeInsets.only(left: 10),
                            child: _statBox(item),
                          )),
                    ],
                  ),
          ),
        ],
      ),
    );
  }

  Widget _heroCopy() => Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            'TEACHING STAFF',
            style: TextStyle(
              color: _darkGreen,
              fontSize: 24,
              fontWeight: FontWeight.w900,
              letterSpacing: 1.2,
            ),
          ),
          const SizedBox(height: 6),
          Text(
            'A visual directory of staff available for lecture planning and academic coordination.',
            style: TextStyle(color: Colors.grey.shade600, fontSize: 14.5, height: 1.45),
          ),
        ],
      );

  Widget _statBox(_StatData item) => Container(
        width: 132,
        padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
        decoration: BoxDecoration(
          color: const Color(0xFFF8FAF8),
          border: Border.all(color: const Color(0xFFE1E8E3)),
        ),
        child: Row(
          children: [
            Icon(item.icon, color: _standardGold, size: 22),
            const SizedBox(width: 10),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(item.value,
                      style: const TextStyle(color: _ink, fontWeight: FontWeight.w900, fontSize: 18)),
                  Text(item.label,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(color: Color(0xFF76847B), fontSize: 10.5, fontWeight: FontWeight.w600)),
                ],
              ),
            ),
          ],
        ),
      );

  Widget _buildToolbar(double width) {
    final search = TextField(
      controller: _searchController,
      onChanged: (_) => setState(() {}),
      decoration: InputDecoration(
        hintText: 'Search staff, campus, school or department...',
        prefixIcon: const Icon(Icons.search_rounded, color: _darkGreen),
        suffixIcon: _searchController.text.isNotEmpty
            ? IconButton(
                tooltip: 'Clear search',
                onPressed: () {
                  _searchController.clear();
                  setState(() {});
                },
                icon: const Icon(Icons.close_rounded),
              )
            : null,
        filled: true,
        fillColor: Colors.white,
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 17),
        border: const OutlineInputBorder(borderRadius: BorderRadius.zero),
        enabledBorder: const OutlineInputBorder(
          borderRadius: BorderRadius.zero,
          borderSide: BorderSide(color: Color(0xFFD7DFDA)),
        ),
        focusedBorder: const OutlineInputBorder(
          borderRadius: BorderRadius.zero,
          borderSide: BorderSide(color: _darkGreen, width: 2),
        ),
      ),
    );

    final campusFilter = DropdownButtonFormField<String>(
      value: _campuses.contains(_campusFilter) ? _campusFilter : 'All Campuses',
      isExpanded: true,
      decoration: const InputDecoration(
        labelText: 'Campus',
        prefixIcon: Icon(Icons.domain_outlined, color: _standardGold),
        filled: true,
        fillColor: Colors.white,
        border: OutlineInputBorder(borderRadius: BorderRadius.zero),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.zero,
          borderSide: BorderSide(color: Color(0xFFD7DFDA)),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.zero,
          borderSide: BorderSide(color: _darkGreen, width: 2),
        ),
      ),
      items: _campuses.map((campus) => DropdownMenuItem(value: campus, child: Text(campus))).toList(),
      onChanged: (value) => setState(() => _campusFilter = value ?? 'All Campuses'),
    );

    final refresh = OutlinedButton.icon(
      onPressed: _loading ? null : _loadStaff,
      icon: const Icon(Icons.refresh_rounded),
      label: const Text('REFRESH'),
      style: OutlinedButton.styleFrom(
        foregroundColor: _darkGreen,
        side: const BorderSide(color: _darkGreen),
        shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
      ),
    );

    if (width < 840) {
      return Column(
        children: [
          search,
          const SizedBox(height: 10),
          Row(children: [Expanded(child: campusFilter), const SizedBox(width: 10), refresh]),
        ],
      );
    }

    return Row(
      children: [
        Expanded(flex: 5, child: search),
        const SizedBox(width: 12),
        Expanded(flex: 2, child: campusFilter),
        const SizedBox(width: 12),
        refresh,
      ],
    );
  }

  Widget _buildContent(double width) {
    if (_loading) {
      return const Center(child: CircularProgressIndicator(color: _darkGreen));
    }

    if (_error != null) {
      return _messagePanel(
        icon: Icons.cloud_off_outlined,
        title: 'Unable to load staff',
        message: _error!,
        actionLabel: 'TRY AGAIN',
        onAction: _loadStaff,
      );
    }

    final staff = _visibleStaff;
    if (_staff.isEmpty) {
      return _messagePanel(
        icon: Icons.people_outline_rounded,
        title: 'No staff records found',
        message: 'Staff added to the system will appear here with their profile picture and campus assignment.',
      );
    }

    if (staff.isEmpty) {
      return _messagePanel(
        icon: Icons.search_off_rounded,
        title: 'No matching staff',
        message: 'Try another name, campus, school or department.',
      );
    }

    final columns = width >= 1420
        ? 4
        : width >= 1050
            ? 3
            : width >= 680
                ? 2
                : 1;

    return GridView.builder(
      padding: const EdgeInsets.only(bottom: 20),
      itemCount: staff.length,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: columns,
        crossAxisSpacing: 16,
        mainAxisSpacing: 16,
        // Give each profile card enough vertical room for the avatar,
        // three assignment rows and the profile action. The previous 312px
        // extent left the inner Column ~8px short on common desktop widths.
        mainAxisExtent: 344,
      ),
      itemBuilder: (context, index) => _StaffCard(
        staff: staff[index],
        name: _staffName(staff[index]),
        campus: _staffCampus(staff[index]),
        school: _staffSchool(staff[index]),
        department: _staffDepartment(staff[index]),
        profile: _profileImage(staff[index]['profile_picture']),
        onOpen: () => _showStaffDetails(staff[index]),
      ),
    );
  }

  Widget _messagePanel({
    required IconData icon,
    required String title,
    required String message,
    String? actionLabel,
    VoidCallback? onAction,
  }) {
    return Center(
      child: Container(
        width: 520,
        padding: const EdgeInsets.all(34),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(color: const Color(0xFFDCE3DE)),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              width: 78,
              height: 78,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: const Color(0xFFF5F8F6),
                border: Border.all(color: const Color(0xFFE1E8E3)),
              ),
              child: Icon(icon, size: 38, color: _darkGreen),
            ),
            const SizedBox(height: 18),
            Text(title,
                textAlign: TextAlign.center,
                style: const TextStyle(color: _ink, fontWeight: FontWeight.w900, fontSize: 20)),
            const SizedBox(height: 8),
            Text(message,
                textAlign: TextAlign.center,
                style: const TextStyle(color: Color(0xFF6F7F75), height: 1.45)),
            if (actionLabel != null && onAction != null) ...[
              const SizedBox(height: 20),
              ElevatedButton.icon(
                onPressed: onAction,
                icon: const Icon(Icons.refresh_rounded),
                label: Text(actionLabel),
                style: ElevatedButton.styleFrom(
                  backgroundColor: _standardGold,
                  foregroundColor: Colors.white,
                  shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }
}

class _StaffCard extends StatefulWidget {
  final Map<String, dynamic> staff;
  final String name;
  final String campus;
  final String school;
  final String department;
  final Widget profile;
  final VoidCallback onOpen;

  const _StaffCard({
    required this.staff,
    required this.name,
    required this.campus,
    required this.school,
    required this.department,
    required this.profile,
    required this.onOpen,
  });

  @override
  State<_StaffCard> createState() => _StaffCardState();
}

class _StaffCardState extends State<_StaffCard> {
  bool _hovered = false;

  @override
  Widget build(BuildContext context) {
    return MouseRegion(
      onEnter: (_) => setState(() => _hovered = true),
      onExit: (_) => setState(() => _hovered = false),
      cursor: SystemMouseCursors.click,
      child: GestureDetector(
        onTap: widget.onOpen,
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 180),
          transform: Matrix4.translationValues(0, _hovered ? -3 : 0, 0),
          decoration: BoxDecoration(
            color: Colors.white,
            border: Border.all(color: _hovered ? _standardGold : const Color(0xFFDCE3DE), width: _hovered ? 1.5 : 1),
            boxShadow: [
              BoxShadow(
                color: _hovered ? const Color(0x19000000) : const Color(0x0D000000),
                blurRadius: _hovered ? 20 : 10,
                offset: const Offset(0, 7),
              ),
            ],
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Container(height: 4, color: _hovered ? _standardGold : _darkGreen),
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.all(20),
                  child: Column(
                    children: [
                      Stack(
                        clipBehavior: Clip.none,
                        children: [
                          Container(
                            width: 92,
                            height: 92,
                            padding: const EdgeInsets.all(3),
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              border: Border.all(color: _standardGold, width: 2),
                            ),
                            child: ClipOval(child: widget.profile),
                          ),
                          Positioned(
                            right: -2,
                            bottom: 4,
                            child: Container(
                              width: 22,
                              height: 22,
                              decoration: BoxDecoration(
                                color: _darkGreen,
                                shape: BoxShape.circle,
                                border: Border.all(color: Colors.white, width: 3),
                              ),
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 15),
                      Text(
                        widget.name,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        textAlign: TextAlign.center,
                        style: const TextStyle(
                          color: _ink,
                          fontWeight: FontWeight.w900,
                          fontSize: 17,
                        ),
                      ),
                      const SizedBox(height: 6),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                        decoration: const BoxDecoration(color: Color(0xFFF4F8F5)),
                        child: const Text(
                          'STAFF',
                          style: TextStyle(
                            color: _darkGreen,
                            fontWeight: FontWeight.w800,
                            fontSize: 10,
                            letterSpacing: 1,
                          ),
                        ),
                      ),
                      const SizedBox(height: 15),
                      _info(Icons.domain_outlined, widget.campus),
                      const SizedBox(height: 8),
                      _info(Icons.account_balance_outlined, widget.school),
                      const SizedBox(height: 8),
                      _info(Icons.account_tree_outlined, widget.department),
                      const Spacer(),
                      Container(height: 1, color: const Color(0xFFE8ECE9)),
                      const SizedBox(height: 11),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(Icons.visibility_outlined, size: 16, color: _hovered ? _standardGold : _darkGreen),
                          const SizedBox(width: 7),
                          Text(
                            'VIEW STAFF PROFILE',
                            style: TextStyle(
                              color: _hovered ? _standardGold : _darkGreen,
                              fontWeight: FontWeight.w800,
                              fontSize: 11,
                              letterSpacing: 0.7,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _info(IconData icon, String text) {
    return Row(
      children: [
        Icon(icon, size: 16, color: _standardGold),
        const SizedBox(width: 8),
        Expanded(
          child: Text(
            text,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: const TextStyle(color: Color(0xFF647269), fontSize: 12.5, fontWeight: FontWeight.w500),
          ),
        ),
      ],
    );
  }
}

class _StatData {
  final IconData icon;
  final String value;
  final String label;

  const _StatData(this.icon, this.value, this.label);
}
