// lib/features/admin/tabs/admin_announcements_tab.dart
// ADMIN-ONLY ANNOUNCEMENT DELETE CENTER
//
// Purpose:
// - Shows every announcement: published, draft, scheduled and expired.
// - Provides NO publishing/editing controls.
// - The only destructive action in this screen is permanent deletion.
// - Verifies the signed-in account is an administrator before loading data.
// - Server-side authorization must still be enforced by api/announcements.php.

import 'dart:async';

import 'package:flutter/material.dart';

import '../../../core/services/campus_announcements_service.dart';

const Color _rvGreen = Color.fromARGB(255, 2, 105, 48);
const Color _rvGold = Color.fromARGB(255, 204, 117, 4);
const Color _rvInk = Color(0xFF182632);
const Color _rvMuted = Color(0xFF66727E);
const Color _rvBorder = Color(0xFFE2E7EC);
const Color _rvPage = Color(0xFFF3F5F7);

class AdminAnnouncementsTab extends StatefulWidget {
  /// Kept for compatibility with the existing parent screen.
  /// The actual administrator identity is verified from the signed-in session.
  final String adminName;

  const AdminAnnouncementsTab({
    super.key,
    this.adminName = 'Administrator',
  });

  @override
  State<AdminAnnouncementsTab> createState() => _AdminAnnouncementsTabState();
}

class _AdminAnnouncementsTabState extends State<AdminAnnouncementsTab> {
  final TextEditingController _searchController = TextEditingController();
  final List<CampusAnnouncement> _announcements = <CampusAnnouncement>[];

  Timer? _refreshTimer;
  bool _checkingAccess = true;
  bool _isAdmin = false;
  bool _loading = true;
  bool _refreshingSilently = false;
  int? _deletingId;
  String? _error;

  String _administratorName = 'Administrator';
  String _administratorRole = '';
  String _statusFilter = 'All Statuses';
  String _campusFilter = 'All Campuses';
  String _categoryFilter = 'All Categories';

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

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

  bool _roleIsAdministrator(String? role) {
    final normalized = (role ?? '')
        .trim()
        .toLowerCase()
        .replaceAll(RegExp(r'\s+'), ' ');

    return <String>{
      'admin',
      'administrator',
      'superadmin',
      'super_admin',
      'super admin',
    }.contains(normalized);
  }

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

    try {
      final me = await CampusAnnouncementsService.getCurrentUser();
      final role = '${me['role'] ?? ''}'.trim();
      final isAdmin = _roleIsAdministrator(role);

      if (!mounted) return;
      setState(() {
        _isAdmin = isAdmin;
        _administratorRole = role;
        _administratorName = '${me['full_name'] ?? me['fullName'] ?? widget.adminName}'.trim();
        if (_administratorName.isEmpty) _administratorName = widget.adminName;
        _checkingAccess = false;
      });

      if (!isAdmin) {
        setState(() => _loading = false);
        return;
      }

      await _loadAllAnnouncements();

      _refreshTimer?.cancel();
      _refreshTimer = Timer.periodic(const Duration(seconds: 30), (_) {
        if (mounted && _isAdmin && !_loading && _deletingId == null) {
          _loadAllAnnouncements(silent: true);
        }
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _checkingAccess = false;
        _loading = false;
        _error = _cleanError(e);
      });
    }
  }

  Future<void> _loadAllAnnouncements({bool silent = false}) async {
    if (!_isAdmin) return;

    if (silent) {
      if (_refreshingSilently) return;
      _refreshingSilently = true;
    } else if (mounted) {
      setState(() {
        _loading = true;
        _error = null;
      });
    }

    try {
      final loaded = <CampusAnnouncement>[];
      var pageNumber = 1;
      var hasMore = true;

      // The backend caps one page at 50. Walk every page so this admin-only
      // screen genuinely contains ALL announcements, not only the first page.
      while (hasMore && pageNumber <= 200) {
        final page = await CampusAnnouncementsService.getAnnouncements(
          scope: 'all',
          page: pageNumber,
          limit: 50,
        );
        loaded.addAll(page.announcements);
        hasMore = page.hasMore;
        pageNumber++;
      }

      // Deletion centre should be chronological rather than pin-prioritised.
      loaded.sort((a, b) => _effectiveDate(b).compareTo(_effectiveDate(a)));

      if (!mounted) return;
      setState(() {
        _announcements
          ..clear()
          ..addAll(loaded);
        _loading = false;
        _error = null;
      });
    } catch (e) {
      if (!mounted) return;
      if (!silent) {
        setState(() {
          _loading = false;
          _error = _cleanError(e);
        });
      }
    } finally {
      _refreshingSilently = false;
    }
  }

  DateTime _effectiveDate(CampusAnnouncement item) {
    return item.publishedAt ??
        item.scheduledAt ??
        item.updatedAt ??
        item.createdAt;
  }

  List<String> get _campuses {
    final values = _announcements
        .map((item) => item.campus.trim())
        .where((value) => value.isNotEmpty)
        .toSet()
        .toList()
      ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
    return <String>['All Campuses', ...values];
  }

  List<String> get _categories {
    final values = _announcements
        .map((item) => item.category.trim())
        .where((value) => value.isNotEmpty)
        .toSet()
        .toList()
      ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
    return <String>['All Categories', ...values];
  }

  List<CampusAnnouncement> get _visibleAnnouncements {
    final query = _searchController.text.trim().toLowerCase();

    return _announcements.where((item) {
      final statusMatches = _statusFilter == 'All Statuses' ||
          item.status.toLowerCase() == _statusFilter.toLowerCase();

      final campusMatches = _campusFilter == 'All Campuses' ||
          item.campus.trim() == _campusFilter;

      final categoryMatches = _categoryFilter == 'All Categories' ||
          item.category.trim() == _categoryFilter;

      if (!statusMatches || !campusMatches || !categoryMatches) return false;
      if (query.isEmpty) return true;

      final searchable = <String>[
        item.title,
        item.body,
        item.authorName,
        item.authorRole,
        item.campus,
        item.category,
        item.priority,
        item.audience,
        item.status,
      ].join(' ').toLowerCase();

      return searchable.contains(query);
    }).toList();
  }

  int _countStatus(String status) => _announcements
      .where((item) => item.status.toLowerCase() == status.toLowerCase())
      .length;

  Future<void> _deleteAnnouncement(CampusAnnouncement item) async {
    if (!_isAdmin || _deletingId != null) return;

    final confirmed = await showDialog<bool>(
          context: context,
          barrierDismissible: false,
          builder: (dialogContext) => AlertDialog(
            backgroundColor: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(22),
            ),
            titlePadding: const EdgeInsets.fromLTRB(24, 24, 24, 0),
            contentPadding: const EdgeInsets.fromLTRB(24, 18, 24, 8),
            actionsPadding: const EdgeInsets.fromLTRB(18, 8, 18, 18),
            title: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  width: 44,
                  height: 44,
                  decoration: BoxDecoration(
                    color: Colors.red.shade50,
                    borderRadius: BorderRadius.circular(14),
                  ),
                  child: Icon(
                    Icons.delete_forever_rounded,
                    color: Colors.red.shade700,
                  ),
                ),
                const SizedBox(width: 12),
                const Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Delete announcement permanently?',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.w900,
                          color: _rvInk,
                        ),
                      ),
                      SizedBox(height: 4),
                      Text(
                        'Administrator action',
                        style: TextStyle(
                          fontSize: 11,
                          color: _rvMuted,
                          fontWeight: FontWeight.w700,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  item.title,
                  style: const TextStyle(
                    fontWeight: FontWeight.w900,
                    color: _rvInk,
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  'Posted by ${item.authorName} • ${_statusLabel(item.status)}',
                  style: const TextStyle(
                    color: _rvMuted,
                    fontSize: 12,
                  ),
                ),
                const SizedBox(height: 16),
                Container(
                  width: double.infinity,
                  padding: const EdgeInsets.all(14),
                  decoration: BoxDecoration(
                    color: Colors.red.shade50,
                    borderRadius: BorderRadius.circular(14),
                    border: Border.all(color: Colors.red.shade100),
                  ),
                  child: const Text(
                    'This cannot be undone. The announcement and its linked likes, comments, notifications and uploaded media will no longer be available.',
                    style: TextStyle(
                      color: Color(0xFF8B2525),
                      fontSize: 12,
                      height: 1.45,
                    ),
                  ),
                ),
              ],
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(dialogContext, false),
                child: const Text('CANCEL'),
              ),
              FilledButton.icon(
                onPressed: () => Navigator.pop(dialogContext, true),
                style: FilledButton.styleFrom(
                  backgroundColor: Colors.red.shade700,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(
                    horizontal: 18,
                    vertical: 13,
                  ),
                ),
                icon: const Icon(Icons.delete_outline_rounded, size: 18),
                label: const Text(
                  'DELETE PERMANENTLY',
                  style: TextStyle(fontWeight: FontWeight.w900),
                ),
              ),
            ],
          ),
        ) ??
        false;

    if (!confirmed || !mounted) return;

    setState(() => _deletingId = item.id);
    try {
      await CampusAnnouncementsService.deleteAnnouncement(item.id);
      if (!mounted) return;
      setState(() {
        _announcements.removeWhere((announcement) => announcement.id == item.id);
        _deletingId = null;
      });
      _showMessage('Announcement deleted permanently.');
    } catch (e) {
      if (!mounted) return;
      setState(() => _deletingId = null);
      _showMessage(_cleanError(e), error: true);
    }
  }

  void _showMessage(String message, {bool error = false}) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: error ? Colors.red.shade700 : _rvGreen,
        behavior: SnackBarBehavior.floating,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_checkingAccess) {
      return const ColoredBox(
        color: _rvPage,
        child: Center(
          child: CircularProgressIndicator(color: _rvGreen),
        ),
      );
    }

    if (!_isAdmin) return _accessDenied();

    return Scaffold(
      backgroundColor: _rvPage,
      body: RefreshIndicator(
        onRefresh: _loadAllAnnouncements,
        color: _rvGreen,
        child: CustomScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          slivers: [
            SliverToBoxAdapter(child: _buildHeroHeader()),
            SliverToBoxAdapter(child: _buildStats()),
            SliverToBoxAdapter(child: _buildFilters()),
            if (_loading)
              const SliverFillRemaining(
                hasScrollBody: false,
                child: Center(
                  child: CircularProgressIndicator(color: _rvGreen),
                ),
              )
            else if (_error != null)
              SliverFillRemaining(
                hasScrollBody: false,
                child: _buildErrorState(),
              )
            else if (_visibleAnnouncements.isEmpty)
              SliverFillRemaining(
                hasScrollBody: false,
                child: _buildEmptyState(),
              )
            else
              SliverPadding(
                padding: const EdgeInsets.fromLTRB(18, 0, 18, 40),
                sliver: SliverList.separated(
                  itemCount: _visibleAnnouncements.length,
                  separatorBuilder: (_, __) => const SizedBox(height: 12),
                  itemBuilder: (context, index) {
                    final item = _visibleAnnouncements[index];
                    return _AdminAnnouncementCard(
                      item: item,
                      deleting: _deletingId == item.id,
                      onDelete: () => _deleteAnnouncement(item),
                    );
                  },
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildHeroHeader() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(18, 18, 18, 12),
      child: Container(
        padding: const EdgeInsets.all(22),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(24),
          border: Border.all(color: _rvBorder),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(.035),
              blurRadius: 24,
              offset: const Offset(0, 8),
            ),
          ],
        ),
        child: LayoutBuilder(
          builder: (context, constraints) {
            final compact = constraints.maxWidth < 760;

            final title = Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Container(
                      width: 42,
                      height: 42,
                      decoration: BoxDecoration(
                        color: _rvGreen.withOpacity(.08),
                        borderRadius: BorderRadius.circular(14),
                      ),
                      child: const Icon(
                        Icons.admin_panel_settings_rounded,
                        color: _rvGreen,
                      ),
                    ),
                    const SizedBox(width: 12),
                    const Expanded(
                      child: Text(
                        'Announcement Control Center',
                        style: TextStyle(
                          fontSize: 22,
                          fontWeight: FontWeight.w900,
                          color: _rvInk,
                          letterSpacing: -.25,
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                const Text(
                  'Administrator-only archive for reviewing every announcement and permanently deleting content when required.',
                  style: TextStyle(
                    color: _rvMuted,
                    fontSize: 12.5,
                    height: 1.55,
                  ),
                ),
                const SizedBox(height: 12),
                Wrap(
                  spacing: 8,
                  runSpacing: 8,
                  children: [
                    _InfoBadge(
                      icon: Icons.verified_user_rounded,
                      text: _administratorName,
                      foreground: _rvGreen,
                      background: _rvGreen.withOpacity(.075),
                    ),
                    _InfoBadge(
                      icon: Icons.security_rounded,
                      text: _administratorRole.isEmpty
                          ? 'Administrator'
                          : _administratorRole,
                      foreground: _rvGold,
                      background: _rvGold.withOpacity(.1),
                    ),
                    const _InfoBadge(
                      icon: Icons.lock_outline_rounded,
                      text: 'ADMIN ONLY',
                      foreground: Color(0xFF9C2D2D),
                      background: Color(0xFFFFEEEE),
                    ),
                  ],
                ),
              ],
            );

            final refresh = OutlinedButton.icon(
              onPressed: _loading ? null : () => _loadAllAnnouncements(),
              style: OutlinedButton.styleFrom(
                foregroundColor: _rvGreen,
                side: const BorderSide(color: _rvBorder),
                padding: const EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 14,
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(14),
                ),
              ),
              icon: const Icon(Icons.refresh_rounded, size: 18),
              label: const Text(
                'REFRESH',
                style: TextStyle(fontWeight: FontWeight.w900),
              ),
            );

            if (compact) {
              return Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  title,
                  const SizedBox(height: 16),
                  refresh,
                ],
              );
            }

            return Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(child: title),
                const SizedBox(width: 18),
                refresh,
              ],
            );
          },
        ),
      ),
    );
  }

  Widget _buildStats() {
    final cards = <Widget>[
      _StatCard(
        label: 'ALL',
        value: '${_announcements.length}',
        icon: Icons.inventory_2_outlined,
        accent: _rvGreen,
      ),
      _StatCard(
        label: 'PUBLISHED',
        value: '${_countStatus('published')}',
        icon: Icons.campaign_outlined,
        accent: const Color(0xFF117A45),
      ),
      _StatCard(
        label: 'DRAFTS',
        value: '${_countStatus('draft')}',
        icon: Icons.edit_note_rounded,
        accent: const Color(0xFF52606D),
      ),
      _StatCard(
        label: 'SCHEDULED',
        value: '${_countStatus('scheduled')}',
        icon: Icons.schedule_rounded,
        accent: _rvGold,
      ),
      _StatCard(
        label: 'EXPIRED',
        value: '${_countStatus('expired')}',
        icon: Icons.history_toggle_off_rounded,
        accent: const Color(0xFF8C5A5A),
      ),
    ];

    return Padding(
      padding: const EdgeInsets.fromLTRB(18, 0, 18, 12),
      child: LayoutBuilder(
        builder: (context, constraints) {
          final width = constraints.maxWidth;
          final columns = width >= 1100
              ? 5
              : width >= 760
                  ? 3
                  : 2;
          final gap = 10.0;
          final cardWidth =
              (width - (gap * (columns - 1))) / columns;

          return Wrap(
            spacing: gap,
            runSpacing: gap,
            children: cards
                .map((card) => SizedBox(width: cardWidth, child: card))
                .toList(),
          );
        },
      ),
    );
  }

  Widget _buildFilters() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(18, 0, 18, 12),
      child: Container(
        padding: const EdgeInsets.all(14),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(20),
          border: Border.all(color: _rvBorder),
        ),
        child: LayoutBuilder(
          builder: (context, constraints) {
            final compact = constraints.maxWidth < 900;

            final search = TextField(
              controller: _searchController,
              onChanged: (_) => setState(() {}),
              decoration: InputDecoration(
                hintText: 'Search title, content, author, campus...',
                prefixIcon: const Icon(Icons.search_rounded, color: _rvGreen),
                suffixIcon: _searchController.text.isEmpty
                    ? null
                    : IconButton(
                        onPressed: () {
                          _searchController.clear();
                          setState(() {});
                        },
                        icon: const Icon(Icons.close_rounded),
                      ),
                filled: true,
                fillColor: const Color(0xFFF7F9FA),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(14),
                  borderSide: const BorderSide(color: _rvBorder),
                ),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(14),
                  borderSide: const BorderSide(color: _rvBorder),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(14),
                  borderSide: const BorderSide(color: _rvGreen, width: 1.3),
                ),
              ),
            );

            final filters = Wrap(
              spacing: 8,
              runSpacing: 8,
              children: [
                _FilterDropdown(
                  width: compact ? 180 : 170,
                  value: _statusFilter,
                  items: const <String>[
                    'All Statuses',
                    'published',
                    'draft',
                    'scheduled',
                    'expired',
                  ],
                  onChanged: (value) {
                    if (value != null) setState(() => _statusFilter = value);
                  },
                ),
                _FilterDropdown(
                  width: compact ? 190 : 180,
                  value: _campuses.contains(_campusFilter)
                      ? _campusFilter
                      : 'All Campuses',
                  items: _campuses,
                  onChanged: (value) {
                    if (value != null) setState(() => _campusFilter = value);
                  },
                ),
                _FilterDropdown(
                  width: compact ? 190 : 180,
                  value: _categories.contains(_categoryFilter)
                      ? _categoryFilter
                      : 'All Categories',
                  items: _categories,
                  onChanged: (value) {
                    if (value != null) setState(() => _categoryFilter = value);
                  },
                ),
              ],
            );

            if (compact) {
              return Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  search,
                  const SizedBox(height: 10),
                  filters,
                  const SizedBox(height: 8),
                  Text(
                    '${_visibleAnnouncements.length} announcement${_visibleAnnouncements.length == 1 ? '' : 's'} shown',
                    style: const TextStyle(
                      color: _rvMuted,
                      fontSize: 11,
                      fontWeight: FontWeight.w700,
                    ),
                  ),
                ],
              );
            }

            return Row(
              children: [
                Expanded(flex: 4, child: search),
                const SizedBox(width: 10),
                Expanded(flex: 5, child: filters),
                const SizedBox(width: 10),
                Text(
                  '${_visibleAnnouncements.length} shown',
                  style: const TextStyle(
                    color: _rvMuted,
                    fontSize: 11,
                    fontWeight: FontWeight.w800,
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }

  Widget _buildErrorState() {
    return Padding(
      padding: const EdgeInsets.all(18),
      child: Center(
        child: Container(
          constraints: const BoxConstraints(maxWidth: 620),
          padding: const EdgeInsets.all(28),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(22),
            border: Border.all(color: _rvBorder),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(Icons.cloud_off_rounded, size: 54, color: Colors.red.shade300),
              const SizedBox(height: 12),
              const Text(
                'Announcements could not be loaded',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.w900,
                  color: _rvInk,
                ),
              ),
              const SizedBox(height: 8),
              Text(
                _error ?? 'Unknown error.',
                textAlign: TextAlign.center,
                style: const TextStyle(color: _rvMuted, height: 1.5),
              ),
              const SizedBox(height: 16),
              FilledButton.icon(
                onPressed: _loadAllAnnouncements,
                style: FilledButton.styleFrom(backgroundColor: _rvGreen),
                icon: const Icon(Icons.refresh_rounded),
                label: const Text('TRY AGAIN'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildEmptyState() {
    return Padding(
      padding: const EdgeInsets.all(18),
      child: Center(
        child: Container(
          constraints: const BoxConstraints(maxWidth: 620),
          padding: const EdgeInsets.symmetric(horizontal: 28, vertical: 54),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(22),
            border: Border.all(color: _rvBorder),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(Icons.campaign_outlined, size: 62, color: Colors.grey.shade300),
              const SizedBox(height: 14),
              const Text(
                'No announcements found',
                style: TextStyle(
                  fontSize: 19,
                  fontWeight: FontWeight.w900,
                  color: _rvInk,
                ),
              ),
              const SizedBox(height: 7),
              const Text(
                'Clear the filters or refresh the archive.',
                textAlign: TextAlign.center,
                style: TextStyle(color: _rvMuted),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _accessDenied() {
    return Scaffold(
      backgroundColor: _rvPage,
      body: Center(
        child: Container(
          constraints: const BoxConstraints(maxWidth: 560),
          margin: const EdgeInsets.all(20),
          padding: const EdgeInsets.all(30),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(24),
            border: Border.all(color: Colors.red.shade100),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(.04),
                blurRadius: 24,
                offset: const Offset(0, 10),
              ),
            ],
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                width: 70,
                height: 70,
                decoration: BoxDecoration(
                  color: Colors.red.shade50,
                  shape: BoxShape.circle,
                ),
                child: Icon(
                  Icons.lock_person_rounded,
                  size: 36,
                  color: Colors.red.shade700,
                ),
              ),
              const SizedBox(height: 18),
              const Text(
                'Administrator access required',
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 21,
                  fontWeight: FontWeight.w900,
                  color: _rvInk,
                ),
              ),
              const SizedBox(height: 8),
              Text(
                _administratorRole.isEmpty
                    ? 'This announcement deletion center is restricted to administrators.'
                    : 'The signed-in role "$_administratorRole" is not permitted to access the announcement deletion center.',
                textAlign: TextAlign.center,
                style: const TextStyle(
                  color: _rvMuted,
                  fontSize: 12.5,
                  height: 1.5,
                ),
              ),
              if (_error != null) ...[
                const SizedBox(height: 12),
                Text(
                  _error!,
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.red.shade700, fontSize: 11),
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }
}

class _AdminAnnouncementCard extends StatelessWidget {
  final CampusAnnouncement item;
  final bool deleting;
  final VoidCallback onDelete;

  const _AdminAnnouncementCard({
    required this.item,
    required this.deleting,
    required this.onDelete,
  });

  @override
  Widget build(BuildContext context) {
    final image = item.images.isEmpty ? null : item.images.first;
    final imagePath = image == null
        ? ''
        : (image.thumbnailPath.trim().isNotEmpty
            ? image.thumbnailPath
            : image.path);

    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(22),
        border: Border.all(color: _rvBorder),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(.025),
            blurRadius: 18,
            offset: const Offset(0, 6),
          ),
        ],
      ),
      child: LayoutBuilder(
        builder: (context, constraints) {
          final compact = constraints.maxWidth < 760;
          final preview = _AnnouncementPreview(
            item: item,
            imagePath: imagePath,
            compact: compact,
          );
          final details = _AnnouncementDetails(item: item);
          final action = SizedBox(
            width: compact ? double.infinity : 150,
            child: FilledButton.icon(
              onPressed: deleting ? null : onDelete,
              style: FilledButton.styleFrom(
                backgroundColor: Colors.red.shade700,
                foregroundColor: Colors.white,
                disabledBackgroundColor: Colors.red.shade100,
                padding: const EdgeInsets.symmetric(vertical: 14),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(13),
                ),
              ),
              icon: deleting
                  ? const SizedBox(
                      width: 16,
                      height: 16,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        color: Colors.white,
                      ),
                    )
                  : const Icon(Icons.delete_outline_rounded, size: 18),
              label: Text(
                deleting ? 'DELETING' : 'DELETE',
                style: const TextStyle(fontWeight: FontWeight.w900),
              ),
            ),
          );

          if (compact) {
            return Padding(
              padding: const EdgeInsets.all(14),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  preview,
                  const SizedBox(height: 14),
                  details,
                  const SizedBox(height: 14),
                  action,
                ],
              ),
            );
          }

          return Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(width: 150, child: preview),
                const SizedBox(width: 18),
                Expanded(child: details),
                const SizedBox(width: 18),
                action,
              ],
            ),
          );
        },
      ),
    );
  }
}

class _AnnouncementPreview extends StatelessWidget {
  final CampusAnnouncement item;
  final String imagePath;
  final bool compact;

  const _AnnouncementPreview({
    required this.item,
    required this.imagePath,
    required this.compact,
  });

  @override
  Widget build(BuildContext context) {
    final height = compact ? 180.0 : 118.0;

    return ClipRRect(
      borderRadius: BorderRadius.circular(16),
      child: SizedBox(
        height: height,
        child: Stack(
          fit: StackFit.expand,
          children: [
            if (imagePath.isNotEmpty)
              Image.network(
                CampusAnnouncementsService.mediaUrl(imagePath),
                fit: BoxFit.cover,
                cacheWidth: compact ? 1100 : 500,
                errorBuilder: (_, __, ___) => _previewFallback(),
              )
            else
              _previewFallback(),
            Positioned(
              left: 8,
              top: 8,
              child: _StatusChip(status: item.status),
            ),
            if (item.media.isNotEmpty)
              Positioned(
                right: 8,
                bottom: 8,
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
                  decoration: BoxDecoration(
                    color: Colors.black.withOpacity(.65),
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: Text(
                    '${item.images.length} photo${item.images.length == 1 ? '' : 's'}${item.video != null ? ' • video' : ''}',
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 9,
                      fontWeight: FontWeight.w900,
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _previewFallback() {
    return Container(
      color: const Color(0xFFF0F3F5),
      child: Center(
        child: Icon(
          item.video != null ? Icons.videocam_outlined : Icons.campaign_outlined,
          size: 44,
          color: Colors.grey.shade400,
        ),
      ),
    );
  }
}

class _AnnouncementDetails extends StatelessWidget {
  final CampusAnnouncement item;
  const _AnnouncementDetails({required this.item});

  @override
  Widget build(BuildContext context) {
    final eventDate = item.publishedAt ??
        item.scheduledAt ??
        item.updatedAt ??
        item.createdAt;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: Text(
                item.title.trim().isEmpty ? 'Untitled announcement' : item.title,
                style: const TextStyle(
                  color: _rvInk,
                  fontSize: 16.5,
                  height: 1.3,
                  fontWeight: FontWeight.w900,
                ),
              ),
            ),
            if (item.isPinned) ...[
              const SizedBox(width: 8),
              const Icon(Icons.push_pin_rounded, size: 18, color: _rvGold),
            ],
          ],
        ),
        const SizedBox(height: 6),
        Text(
          item.body,
          maxLines: 3,
          overflow: TextOverflow.ellipsis,
          style: const TextStyle(
            color: _rvMuted,
            fontSize: 11.5,
            height: 1.5,
          ),
        ),
        const SizedBox(height: 11),
        Wrap(
          spacing: 6,
          runSpacing: 6,
          children: [
            _MetaPill(icon: Icons.person_outline_rounded, text: item.authorName),
            _MetaPill(
              icon: Icons.location_on_outlined,
              text: item.campus.trim().isEmpty ? 'Campus not set' : item.campus,
            ),
            _MetaPill(icon: Icons.category_outlined, text: item.category),
            _MetaPill(icon: Icons.priority_high_rounded, text: item.priority),
            _MetaPill(icon: Icons.groups_2_outlined, text: item.audience),
          ],
        ),
        const SizedBox(height: 10),
        Row(
          children: [
            Icon(Icons.schedule_rounded, size: 14, color: Colors.grey.shade500),
            const SizedBox(width: 5),
            Text(
              _formatDateTime(eventDate),
              style: const TextStyle(
                color: _rvMuted,
                fontSize: 10.5,
                fontWeight: FontWeight.w700,
              ),
            ),
            const SizedBox(width: 14),
            const Icon(Icons.favorite_border_rounded, size: 14, color: _rvMuted),
            const SizedBox(width: 4),
            Text('${item.likeCount}', style: const TextStyle(color: _rvMuted, fontSize: 10.5)),
            const SizedBox(width: 12),
            const Icon(Icons.mode_comment_outlined, size: 14, color: _rvMuted),
            const SizedBox(width: 4),
            Text('${item.commentCount}', style: const TextStyle(color: _rvMuted, fontSize: 10.5)),
          ],
        ),
      ],
    );
  }
}

class _StatusChip extends StatelessWidget {
  final String status;
  const _StatusChip({required this.status});

  @override
  Widget build(BuildContext context) {
    final normalized = status.toLowerCase();
    late final Color foreground;
    late final Color background;

    switch (normalized) {
      case 'published':
        foreground = _rvGreen;
        background = const Color(0xFFE9F6EF);
        break;
      case 'scheduled':
        foreground = _rvGold;
        background = const Color(0xFFFFF3E4);
        break;
      case 'draft':
        foreground = const Color(0xFF52606D);
        background = const Color(0xFFEEF1F4);
        break;
      case 'expired':
        foreground = const Color(0xFF8C4D4D);
        background = const Color(0xFFF8ECEC);
        break;
      default:
        foreground = _rvMuted;
        background = const Color(0xFFF0F2F4);
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
      decoration: BoxDecoration(
        color: background,
        borderRadius: BorderRadius.circular(999),
      ),
      child: Text(
        _statusLabel(status).toUpperCase(),
        style: TextStyle(
          color: foreground,
          fontSize: 8.8,
          fontWeight: FontWeight.w900,
          letterSpacing: .45,
        ),
      ),
    );
  }
}

class _StatCard extends StatelessWidget {
  final String label;
  final String value;
  final IconData icon;
  final Color accent;

  const _StatCard({
    required this.label,
    required this.value,
    required this.icon,
    required this.accent,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(18),
        border: Border.all(color: _rvBorder),
      ),
      child: Row(
        children: [
          Container(
            width: 38,
            height: 38,
            decoration: BoxDecoration(
              color: accent.withOpacity(.09),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Icon(icon, color: accent, size: 19),
          ),
          const SizedBox(width: 10),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  value,
                  style: const TextStyle(
                    color: _rvInk,
                    fontSize: 20,
                    fontWeight: FontWeight.w900,
                  ),
                ),
                const SizedBox(height: 1),
                Text(
                  label,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(
                    color: _rvMuted,
                    fontSize: 8.8,
                    fontWeight: FontWeight.w900,
                    letterSpacing: .45,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class _InfoBadge extends StatelessWidget {
  final IconData icon;
  final String text;
  final Color foreground;
  final Color background;

  const _InfoBadge({
    required this.icon,
    required this.text,
    required this.foreground,
    required this.background,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7),
      decoration: BoxDecoration(
        color: background,
        borderRadius: BorderRadius.circular(999),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 14, color: foreground),
          const SizedBox(width: 5),
          Text(
            text,
            style: TextStyle(
              color: foreground,
              fontSize: 9.7,
              fontWeight: FontWeight.w900,
            ),
          ),
        ],
      ),
    );
  }
}

class _MetaPill extends StatelessWidget {
  final IconData icon;
  final String text;

  const _MetaPill({required this.icon, required this.text});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
      decoration: BoxDecoration(
        color: const Color(0xFFF5F7F9),
        borderRadius: BorderRadius.circular(999),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 12, color: _rvMuted),
          const SizedBox(width: 4),
          ConstrainedBox(
            constraints: const BoxConstraints(maxWidth: 180),
            child: Text(
              text.trim().isEmpty ? 'Not set' : text,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(
                color: _rvMuted,
                fontSize: 9.6,
                fontWeight: FontWeight.w700,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _FilterDropdown extends StatelessWidget {
  final double width;
  final String value;
  final List<String> items;
  final ValueChanged<String?> onChanged;

  const _FilterDropdown({
    required this.width,
    required this.value,
    required this.items,
    required this.onChanged,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: width,
      padding: const EdgeInsets.symmetric(horizontal: 11),
      decoration: BoxDecoration(
        color: const Color(0xFFF7F9FA),
        borderRadius: BorderRadius.circular(13),
        border: Border.all(color: _rvBorder),
      ),
      child: DropdownButtonHideUnderline(
        child: DropdownButton<String>(
          value: items.contains(value) ? value : items.first,
          isExpanded: true,
          icon: const Icon(Icons.keyboard_arrow_down_rounded, size: 18),
          style: const TextStyle(
            color: _rvInk,
            fontSize: 11,
            fontWeight: FontWeight.w700,
          ),
          items: items
              .map(
                (item) => DropdownMenuItem<String>(
                  value: item,
                  child: Text(
                    _dropdownLabel(item),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              )
              .toList(),
          onChanged: onChanged,
        ),
      ),
    );
  }
}

String _dropdownLabel(String value) {
  if (value == 'published' ||
      value == 'draft' ||
      value == 'scheduled' ||
      value == 'expired') {
    return _statusLabel(value);
  }
  return value;
}

String _statusLabel(String value) {
  switch (value.toLowerCase()) {
    case 'published':
      return 'Published';
    case 'draft':
      return 'Draft';
    case 'scheduled':
      return 'Scheduled';
    case 'expired':
      return 'Expired';
    default:
      return value.trim().isEmpty ? 'Unknown' : value;
  }
}

String _formatDateTime(DateTime value) {
  final date = value.toLocal();
  const months = <String>[
    'Jan',
    'Feb',
    'Mar',
    'Apr',
    'May',
    'Jun',
    'Jul',
    'Aug',
    'Sep',
    'Oct',
    'Nov',
    'Dec',
  ];

  final hour = date.hour == 0
      ? 12
      : date.hour > 12
          ? date.hour - 12
          : date.hour;
  final minute = date.minute.toString().padLeft(2, '0');
  final suffix = date.hour >= 12 ? 'PM' : 'AM';

  return '${date.day} ${months[date.month - 1]} ${date.year} • $hour:$minute $suffix';
}

String _cleanError(Object error) {
  var text = error.toString().trim();
  if (text.startsWith('Exception: ')) text = text.substring(11);
  return text;
}
