// lib/features/admin/tabs/admin_events_tab.dart

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

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

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

const Color _eventGreen = Color.fromARGB(255, 2, 105, 48);
const Color _eventGold = Color.fromARGB(255, 204, 117, 4);
const Color _eventPage = Color(0xFFF4F6F5);
const Color _eventBorder = Color(0xFFE1E6E3);
const Color _eventText = Color(0xFF203128);
const Color _eventMuted = Color(0xFF6C7770);

Map<String, dynamic> _decodeAdminEventsResponse(Uint8List bytes) {
  final text = utf8.decode(bytes, allowMalformed: true).trim();
  final decoded = jsonDecode(text);
  if (decoded is Map<String, dynamic>) return decoded;
  if (decoded is Map) {
    return decoded.map((key, value) => MapEntry(key.toString(), value));
  }
  if (decoded is List) {
    return <String, dynamic>{'data': decoded};
  }
  throw const FormatException('Invalid events response.');
}

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

  @override
  State<AdminEventsTab> createState() => _AdminEventsTabState();
}

class _AdminEventsTabState extends State<AdminEventsTab> {
  final TextEditingController _searchController = TextEditingController();
  final ScrollController _scrollController = ScrollController();

  final List<Map<String, dynamic>> _events = <Map<String, dynamic>>[];
  Map<String, dynamic>? _currentUser;

  bool _checkingAccess = true;
  bool _loading = true;
  bool _accessDenied = false;
  String? _error;
  int? _deletingId;

  String _statusFilter = 'All';
  String _campusFilter = 'All Campuses';
  String _categoryFilter = 'All Categories';
  Timer? _refreshTimer;

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

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

  Future<void> _initialize() async {
    await _checkAdministratorAccess();
    if (!mounted || _accessDenied) return;
    await _loadAllEvents();
    _refreshTimer = Timer.periodic(const Duration(seconds: 30), (_) {
      if (mounted && !_loading && _deletingId == null) {
        _loadAllEvents(silent: true);
      }
    });
  }

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

    try {
      final response = await ApiClient.offlineFirstGet(
            Uri.parse('${ApiClient.baseUrl}/api/users.php/me'),
            headers: await ApiClient.getHeaders(),
          )
          .timeout(const Duration(seconds: 15));

      await ApiClient.handleUnauthorized(response);

      if (response.statusCode != 200) {
        throw Exception(_responseMessage(response, 'Unable to verify administrator access.'));
      }

      final dynamic decoded = jsonDecode(response.body);
      if (decoded is! Map) {
        throw const FormatException('Current-user response is invalid.');
      }

      final user = decoded.map((key, value) => MapEntry(key.toString(), value));
      final role = _text(user['role']);
      final allowed = _isAdminRole(role);

      if (!mounted) return;
      setState(() {
        _currentUser = user;
        _accessDenied = !allowed;
        _checkingAccess = false;
        if (!allowed) _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _checkingAccess = false;
        _loading = false;
        _accessDenied = true;
        _error = _cleanError(e);
      });
    }
  }

  bool _isAdminRole(String role) {
    final normalized = role.toLowerCase().replaceAll(RegExp(r'[\s_-]+'), '');
    return normalized == 'admin' ||
        normalized == 'administrator' ||
        normalized == 'superadmin';
  }

  Future<void> _loadAllEvents({bool silent = false}) async {
    if (_accessDenied) return;

    if (!silent && mounted) {
      setState(() {
        _loading = true;
        _error = null;
      });
    }

    try {
      final all = <Map<String, dynamic>>[];
      var page = 1;
      var hasMore = true;

      // events_feed.php intentionally caps each response at 30 records.
      while (hasMore && page <= 50) {
        final uri = Uri.parse('${ApiClient.baseUrl}/api/events_feed.php').replace(
          queryParameters: <String, String>{
            'scope': 'all',
            'page': '$page',
            'limit': '30',
          },
        );

        final response = await ApiClient.offlineFirstGet(uri, headers: await ApiClient.getHeaders())
            .timeout(const Duration(seconds: 20));

        await ApiClient.handleUnauthorized(response);

        if (response.statusCode == 403) {
          if (!mounted) return;
          setState(() {
            _accessDenied = true;
            _loading = false;
            _error = _responseMessage(
              response,
              'Administrator access is required to view all events.',
            );
          });
          return;
        }

        if (response.statusCode != 200) {
          throw Exception(_responseMessage(response, 'Unable to load the event archive.'));
        }

        final decoded = await compute(_decodeAdminEventsResponse, response.bodyBytes);
        final rawRows = decoded['data'];
        if (rawRows is List) {
          for (final raw in rawRows) {
            if (raw is Map) {
              all.add(raw.map((key, value) => MapEntry(key.toString(), value)));
            }
          }
        }

        final pagination = decoded['pagination'];
        if (pagination is Map) {
          hasMore = _bool(pagination['has_more']);
        } else {
          hasMore = rawRows is List && rawRows.length >= 30;
        }
        page += 1;
      }

      all.sort((a, b) {
        final aDate = _parseDate(a['created_at']) ?? _parseDate(a['event_date']);
        final bDate = _parseDate(b['created_at']) ?? _parseDate(b['event_date']);
        if (aDate == null && bDate == null) {
          return _int(b['id']).compareTo(_int(a['id']));
        }
        if (aDate == null) return 1;
        if (bDate == null) return -1;
        final byDate = bDate.compareTo(aDate);
        return byDate != 0 ? byDate : _int(b['id']).compareTo(_int(a['id']));
      });

      if (!mounted) return;
      setState(() {
        _events
          ..clear()
          ..addAll(all);
        _loading = false;
        _error = null;
      });
    } catch (e) {
      if (!mounted) return;
      if (silent) return;
      setState(() {
        _loading = false;
        _error = _cleanError(e);
      });
    }
  }

  Future<void> _confirmDelete(Map<String, dynamic> event) async {
    final title = _text(event['title'], 'Untitled event');
    final id = _int(event['id']);
    if (id <= 0 || _deletingId != null) return;

    final confirmed = await showDialog<bool>(
          context: context,
          barrierDismissible: false,
          builder: (dialogContext) => AlertDialog(
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
            titlePadding: const EdgeInsets.fromLTRB(24, 24, 24, 8),
            contentPadding: const EdgeInsets.fromLTRB(24, 8, 24, 8),
            actionsPadding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
            title: const Row(
              children: [
                Icon(Icons.delete_forever_rounded, color: Colors.redAccent),
                SizedBox(width: 10),
                Expanded(
                  child: Text(
                    'Permanently delete event?',
                    style: TextStyle(fontSize: 19, fontWeight: FontWeight.w900),
                  ),
                ),
              ],
            ),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '"$title" will be permanently removed from the event feed.',
                  style: const TextStyle(height: 1.5),
                ),
                const SizedBox(height: 12),
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: Colors.red.shade50,
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(color: Colors.red.shade100),
                  ),
                  child: const Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Icon(Icons.warning_amber_rounded, color: Colors.redAccent, size: 20),
                      SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          'Pictures, video references, likes, comments, replies, mentions and event notifications linked to this event are also removed. This cannot be undone.',
                          style: TextStyle(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.redAccent),
                icon: const Icon(Icons.delete_forever_rounded),
                label: const Text('DELETE PERMANENTLY'),
              ),
            ],
          ),
        ) ??
        false;

    if (!confirmed || !mounted) return;
    await _deleteEvent(id, title);
  }

  Future<void> _deleteEvent(int id, String title) async {
    setState(() => _deletingId = id);

    try {
      final response = await http
          .delete(
            Uri.parse('${ApiClient.baseUrl}/api/events_feed.php?id=$id'),
            headers: await ApiClient.getHeaders(),
          )
          .timeout(const Duration(seconds: 25));

      await ApiClient.handleUnauthorized(response);

      if (response.statusCode == 403) {
        throw Exception('Only an administrator can permanently delete events.');
      }
      if (response.statusCode != 200) {
        throw Exception(_responseMessage(response, 'Unable to delete this event.'));
      }

      if (!mounted) return;
      setState(() {
        _events.removeWhere((item) => _int(item['id']) == id);
        _deletingId = null;
      });

      _snack('"$title" was permanently deleted.');
    } catch (e) {
      if (!mounted) return;
      setState(() => _deletingId = null);
      _snack(_cleanError(e), error: true);
    }
  }

  List<Map<String, dynamic>> get _filteredEvents {
    final query = _searchController.text.trim().toLowerCase();

    return _events.where((event) {
      final status = _displayStatus(event);
      final campus = _text(event['campus'], 'University Wide');
      final category = _text(event['category'], 'General');

      if (_statusFilter != 'All' && status != _statusFilter) return false;
      if (_campusFilter != 'All Campuses' && campus != _campusFilter) return false;
      if (_categoryFilter != 'All Categories' && category != _categoryFilter) return false;

      if (query.isEmpty) return true;
      final haystack = <String>[
        _text(event['title']),
        _text(event['description']),
        _text(event['author_name']),
        campus,
        category,
        _text(event['location']),
        _text(event['speakers']),
      ].join(' ').toLowerCase();
      return haystack.contains(query);
    }).toList();
  }

  List<String> get _campuses {
    final values = _events
        .map((event) => _text(event['campus'], 'University Wide'))
        .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 = _events
        .map((event) => _text(event['category'], 'General'))
        .where((value) => value.isNotEmpty)
        .toSet()
        .toList()
      ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
    return <String>['All Categories', ...values];
  }

  int _countStatus(String status) =>
      _events.where((event) => _displayStatus(event) == status).length;

  String _displayStatus(Map<String, dynamic> event) {
    final raw = _text(event['status']).toLowerCase();
    if (raw == 'draft') return 'Draft';
    if (!_bool(event['is_active'] ?? true)) return 'Inactive';

    final date = _parseDate(event['event_date']);
    if (date != null && date.isBefore(DateTime.now())) return 'Past';
    return 'Upcoming';
  }

  Color _statusColor(String status) {
    switch (status) {
      case 'Upcoming':
        return _eventGreen;
      case 'Past':
        return const Color(0xFF5F6C76);
      case 'Draft':
        return const Color(0xFFD07B00);
      case 'Inactive':
        return const Color(0xFF8A5660);
      default:
        return _eventMuted;
    }
  }

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

    if (_accessDenied) return _accessDeniedView();

    return Scaffold(
      backgroundColor: _eventPage,
      body: LayoutBuilder(
        builder: (context, constraints) {
          final compact = constraints.maxWidth < 760;
          final horizontal = compact ? 12.0 : 24.0;

          return RefreshIndicator(
            color: _eventGreen,
            onRefresh: _loadAllEvents,
            child: ListView(
              controller: _scrollController,
              physics: const AlwaysScrollableScrollPhysics(),
              padding: EdgeInsets.fromLTRB(horizontal, 20, horizontal, 90),
              children: [
                _buildHeader(compact),
                const SizedBox(height: 16),
                _buildStats(compact),
                const SizedBox(height: 16),
                _buildFilters(compact),
                const SizedBox(height: 16),
                if (_loading)
                  const Padding(
                    padding: EdgeInsets.symmetric(vertical: 120),
                    child: Center(child: CircularProgressIndicator(color: _eventGreen)),
                  )
                else if (_error != null)
                  _buildErrorState()
                else if (_filteredEvents.isEmpty)
                  _buildEmptyState()
                else
                  ..._filteredEvents.map(
                    (event) => Padding(
                      padding: const EdgeInsets.only(bottom: 12),
                      child: _EventAdminCard(
                        event: event,
                        deleting: _deletingId == _int(event['id']),
                        status: _displayStatus(event),
                        statusColor: _statusColor(_displayStatus(event)),
                        onDelete: () => _confirmDelete(event),
                        onView: () => _showEventDetails(event),
                      ),
                    ),
                  ),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildHeader(bool compact) {
    final adminName = _text(
      _currentUser?['full_name'] ?? _currentUser?['fullName'],
      'Administrator',
    );

    return Container(
      padding: EdgeInsets.all(compact ? 18 : 24),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(22),
        border: Border.all(color: _eventBorder),
        boxShadow: const [
          BoxShadow(color: Color(0x0A000000), blurRadius: 20, offset: Offset(0, 7)),
        ],
      ),
      child: compact
          ? Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _headerCopy(adminName),
                const SizedBox(height: 16),
                _refreshButton(),
              ],
            )
          : Row(
              children: [
                Expanded(child: _headerCopy(adminName)),
                const SizedBox(width: 20),
                _refreshButton(),
              ],
            ),
    );
  }

  Widget _headerCopy(String adminName) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Wrap(
          spacing: 8,
          runSpacing: 8,
          crossAxisAlignment: WrapCrossAlignment.center,
          children: [
            const Text(
              'EVENT CONTROL CENTER',
              style: TextStyle(
                color: _eventText,
                fontSize: 22,
                fontWeight: FontWeight.w900,
                letterSpacing: .8,
              ),
            ),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
              decoration: BoxDecoration(
                color: _eventGreen.withOpacity(.08),
                borderRadius: BorderRadius.circular(999),
                border: Border.all(color: _eventGreen.withOpacity(.20)),
              ),
              child: const Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(Icons.admin_panel_settings_rounded, color: _eventGreen, size: 15),
                  SizedBox(width: 5),
                  Text(
                    'ADMIN ONLY',
                    style: TextStyle(
                      color: _eventGreen,
                      fontSize: 10,
                      fontWeight: FontWeight.w900,
                      letterSpacing: .8,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
        const SizedBox(height: 8),
        const Text(
          'Review the complete Rockview event archive. This workspace does not create, edit or publish events; its only management action is permanent deletion.',
          style: TextStyle(color: _eventMuted, height: 1.5, fontSize: 12.5),
        ),
        const SizedBox(height: 12),
        Row(
          children: [
            const CircleAvatar(
              radius: 16,
              backgroundColor: Color(0xFFE9F4EE),
              child: Icon(Icons.verified_user_rounded, color: _eventGreen, size: 17),
            ),
            const SizedBox(width: 9),
            Expanded(
              child: Text(
                '$adminName • Administrator event moderation',
                style: const TextStyle(
                  color: _eventText,
                  fontWeight: FontWeight.w800,
                  fontSize: 11.5,
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _refreshButton() {
    return FilledButton.icon(
      onPressed: _loading ? null : () => _loadAllEvents(),
      style: FilledButton.styleFrom(
        backgroundColor: _eventGreen,
        foregroundColor: Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 15),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
      ),
      icon: const Icon(Icons.refresh_rounded),
      label: const Text('REFRESH', style: TextStyle(fontWeight: FontWeight.w900)),
    );
  }

  Widget _buildStats(bool compact) {
    final items = <_EventStatData>[
      _EventStatData('All events', _events.length, Icons.event_note_rounded, _eventText),
      _EventStatData('Upcoming', _countStatus('Upcoming'), Icons.event_available_rounded, _eventGreen),
      _EventStatData('Past', _countStatus('Past'), Icons.history_rounded, const Color(0xFF5F6C76)),
      _EventStatData('Drafts', _countStatus('Draft'), Icons.edit_calendar_rounded, const Color(0xFFD07B00)),
      _EventStatData('Inactive', _countStatus('Inactive'), Icons.visibility_off_outlined, const Color(0xFF8A5660)),
    ];

    return LayoutBuilder(
      builder: (context, constraints) {
        final width = compact
            ? (constraints.maxWidth - 10) / 2
            : (constraints.maxWidth - 48) / 5;
        return Wrap(
          spacing: 12,
          runSpacing: 12,
          children: items
              .map((item) => SizedBox(width: width.clamp(140.0, 260.0).toDouble(), child: _EventStatCard(data: item)))
              .toList(),
        );
      },
    );
  }

  Widget _buildFilters(bool compact) {
    return Container(
      padding: EdgeInsets.all(compact ? 14 : 18),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: _eventBorder),
      ),
      child: Column(
        children: [
          TextField(
            controller: _searchController,
            onChanged: (_) => setState(() {}),
            decoration: InputDecoration(
              hintText: 'Search title, author, campus, venue or speaker...',
              prefixIcon: const Icon(Icons.search_rounded, color: _eventGreen),
              suffixIcon: _searchController.text.isEmpty
                  ? null
                  : IconButton(
                      tooltip: 'Clear search',
                      onPressed: () {
                        _searchController.clear();
                        setState(() {});
                      },
                      icon: const Icon(Icons.close_rounded),
                    ),
              filled: true,
              fillColor: const Color(0xFFF8FAF9),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(14),
                borderSide: const BorderSide(color: _eventBorder),
              ),
              enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(14),
                borderSide: const BorderSide(color: _eventBorder),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(14),
                borderSide: const BorderSide(color: _eventGreen, width: 1.3),
              ),
            ),
          ),
          const SizedBox(height: 12),
          if (compact)
            Column(
              children: [
                _filterDropdown(
                  value: _statusFilter,
                  values: const ['All', 'Upcoming', 'Past', 'Draft', 'Inactive'],
                  icon: Icons.filter_alt_outlined,
                  onChanged: (value) => setState(() => _statusFilter = value),
                ),
                const SizedBox(height: 10),
                _filterDropdown(
                  value: _campusFilter,
                  values: _campuses,
                  icon: Icons.domain_outlined,
                  onChanged: (value) => setState(() => _campusFilter = value),
                ),
                const SizedBox(height: 10),
                _filterDropdown(
                  value: _categoryFilter,
                  values: _categories,
                  icon: Icons.category_outlined,
                  onChanged: (value) => setState(() => _categoryFilter = value),
                ),
              ],
            )
          else
            Row(
              children: [
                Expanded(
                  child: _filterDropdown(
                    value: _statusFilter,
                    values: const ['All', 'Upcoming', 'Past', 'Draft', 'Inactive'],
                    icon: Icons.filter_alt_outlined,
                    onChanged: (value) => setState(() => _statusFilter = value),
                  ),
                ),
                const SizedBox(width: 10),
                Expanded(
                  child: _filterDropdown(
                    value: _campusFilter,
                    values: _campuses,
                    icon: Icons.domain_outlined,
                    onChanged: (value) => setState(() => _campusFilter = value),
                  ),
                ),
                const SizedBox(width: 10),
                Expanded(
                  child: _filterDropdown(
                    value: _categoryFilter,
                    values: _categories,
                    icon: Icons.category_outlined,
                    onChanged: (value) => setState(() => _categoryFilter = value),
                  ),
                ),
              ],
            ),
          const SizedBox(height: 12),
          Row(
            children: [
              const Icon(Icons.security_rounded, color: _eventGreen, size: 18),
              const SizedBox(width: 8),
              Expanded(
                child: Text(
                  '${_filteredEvents.length} of ${_events.length} events shown • Auto-refresh every 30 seconds',
                  style: const TextStyle(color: _eventMuted, fontSize: 11.5, fontWeight: FontWeight.w700),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _filterDropdown({
    required String value,
    required List<String> values,
    required IconData icon,
    required ValueChanged<String> onChanged,
  }) {
    final safeValues = values.contains(value) ? values : <String>[value, ...values];
    return Container(
      height: 48,
      padding: const EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
        color: const Color(0xFFF8FAF9),
        borderRadius: BorderRadius.circular(13),
        border: Border.all(color: _eventBorder),
      ),
      child: Row(
        children: [
          Icon(icon, color: _eventGreen, size: 18),
          const SizedBox(width: 8),
          Expanded(
            child: DropdownButtonHideUnderline(
              child: DropdownButton<String>(
                value: value,
                isExpanded: true,
                items: safeValues
                    .toSet()
                    .map(
                      (item) => DropdownMenuItem<String>(
                        value: item,
                        child: Text(item, overflow: TextOverflow.ellipsis),
                      ),
                    )
                    .toList(),
                onChanged: (newValue) {
                  if (newValue != null) onChanged(newValue);
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _accessDeniedView() {
    return ColoredBox(
      color: _eventPage,
      child: Center(
        child: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 520),
          child: Container(
            margin: const EdgeInsets.all(20),
            padding: const EdgeInsets.all(30),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(22),
              border: Border.all(color: _eventBorder),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  width: 72,
                  height: 72,
                  decoration: BoxDecoration(
                    color: Colors.red.shade50,
                    shape: BoxShape.circle,
                  ),
                  child: const Icon(Icons.lock_person_rounded, color: Colors.redAccent, size: 38),
                ),
                const SizedBox(height: 18),
                const Text(
                  'Administrator access required',
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 20, fontWeight: FontWeight.w900, color: _eventText),
                ),
                const SizedBox(height: 8),
                Text(
                  _error ?? 'Only administrators can open the Event Delete Center or permanently delete event records.',
                  textAlign: TextAlign.center,
                  style: const TextStyle(color: _eventMuted, height: 1.5),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildErrorState() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 60),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: _eventBorder),
      ),
      child: Column(
        children: [
          Icon(Icons.cloud_off_rounded, size: 54, color: Colors.red.shade300),
          const SizedBox(height: 14),
          const Text('Event archive could not be loaded', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w900)),
          const SizedBox(height: 8),
          Text(_error!, textAlign: TextAlign.center, style: const TextStyle(color: _eventMuted, height: 1.5)),
          const SizedBox(height: 16),
          FilledButton.icon(
            onPressed: () => _loadAllEvents(),
            style: FilledButton.styleFrom(backgroundColor: _eventGreen),
            icon: const Icon(Icons.refresh_rounded),
            label: const Text('TRY AGAIN'),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyState() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 70),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: _eventBorder),
      ),
      child: Column(
        children: [
          Icon(Icons.event_busy_outlined, size: 58, color: Colors.grey.shade300),
          const SizedBox(height: 14),
          const Text('No events match these filters', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w900)),
          const SizedBox(height: 7),
          const Text('Clear the search or choose another status, campus or category.', textAlign: TextAlign.center, style: TextStyle(color: _eventMuted)),
        ],
      ),
    );
  }

  void _showEventDetails(Map<String, dynamic> event) {
    final status = _displayStatus(event);
    final statusColor = _statusColor(status);
    showDialog<void>(
      context: context,
      builder: (context) => Dialog(
        backgroundColor: Colors.white,
        insetPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 24),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(22)),
        child: ConstrainedBox(
          constraints: BoxConstraints(
            maxWidth: 780,
            maxHeight: MediaQuery.of(context).size.height * .88,
          ),
          child: Column(
            children: [
              Container(
                padding: const EdgeInsets.fromLTRB(20, 18, 12, 18),
                decoration: const BoxDecoration(
                  border: Border(bottom: BorderSide(color: _eventBorder)),
                ),
                child: Row(
                  children: [
                    const Icon(Icons.event_note_rounded, color: _eventGreen),
                    const SizedBox(width: 10),
                    const Expanded(
                      child: Text('Event details', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w900)),
                    ),
                    IconButton(onPressed: () => Navigator.pop(context), icon: const Icon(Icons.close_rounded)),
                  ],
                ),
              ),
              Expanded(
                child: SingleChildScrollView(
                  padding: const EdgeInsets.all(22),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _EventStatusBadge(label: status, color: statusColor),
                      const SizedBox(height: 12),
                      Text(
                        _text(event['title'], 'Untitled event'),
                        style: const TextStyle(fontSize: 24, height: 1.25, fontWeight: FontWeight.w900, color: _eventText),
                      ),
                      const SizedBox(height: 12),
                      Wrap(
                        spacing: 8,
                        runSpacing: 8,
                        children: [
                          _detailPill(Icons.schedule_rounded, _formatDate(event['event_date'])),
                          _detailPill(Icons.domain_outlined, _text(event['campus'], 'University Wide')),
                          _detailPill(Icons.location_on_outlined, _text(event['location'], 'Location not provided')),
                          _detailPill(Icons.category_outlined, _text(event['category'], 'General')),
                        ],
                      ),
                      const SizedBox(height: 18),
                      Text(
                        _text(event['description'], 'No description provided.'),
                        style: const TextStyle(color: Color(0xFF526159), height: 1.65, fontSize: 13.5),
                      ),
                      if (_text(event['speakers']).isNotEmpty) ...[
                        const SizedBox(height: 18),
                        const Text('Speakers / Hosts', style: TextStyle(fontWeight: FontWeight.w900)),
                        const SizedBox(height: 5),
                        Text(_text(event['speakers']), style: const TextStyle(color: _eventMuted, height: 1.5)),
                      ],
                      const SizedBox(height: 20),
                      const Divider(),
                      const SizedBox(height: 12),
                      Text(
                        'Created by ${_text(event['author_name'], 'Rockview Events')} • ${_text(event['author_role'], 'staff')}',
                        style: const TextStyle(fontWeight: FontWeight.w800, color: _eventText),
                      ),
                      const SizedBox(height: 5),
                      Text(
                        'Created ${_formatDate(event['created_at'])} • ${_int(event['like_count'])} likes • ${_int(event['comment_count'])} comments • ${_mediaCount(event)} media file${_mediaCount(event) == 1 ? '' : 's'}',
                        style: const TextStyle(color: _eventMuted, fontSize: 11.5),
                      ),
                    ],
                  ),
                ),
              ),
              Container(
                padding: const EdgeInsets.all(16),
                decoration: const BoxDecoration(border: Border(top: BorderSide(color: _eventBorder))),
                child: Row(
                  children: [
                    TextButton(onPressed: () => Navigator.pop(context), child: const Text('CLOSE')),
                    const Spacer(),
                    FilledButton.icon(
                      onPressed: _deletingId == null
                          ? () {
                              Navigator.pop(context);
                              _confirmDelete(event);
                            }
                          : null,
                      style: FilledButton.styleFrom(backgroundColor: Colors.redAccent),
                      icon: const Icon(Icons.delete_forever_rounded),
                      label: const Text('DELETE EVENT'),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _detailPill(IconData icon, String text) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7),
      decoration: BoxDecoration(
        color: const Color(0xFFF7F9F8),
        borderRadius: BorderRadius.circular(999),
        border: Border.all(color: _eventBorder),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, color: _eventGreen, size: 15),
          const SizedBox(width: 6),
          ConstrainedBox(
            constraints: const BoxConstraints(maxWidth: 260),
            child: Text(
              text,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(fontSize: 10.5, fontWeight: FontWeight.w700),
            ),
          ),
        ],
      ),
    );
  }

  void _snack(String message, {bool error = false}) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message, style: const TextStyle(fontWeight: FontWeight.w700)),
        backgroundColor: error ? Colors.red.shade700 : _eventGreen,
        behavior: SnackBarBehavior.floating,
      ),
    );
  }
}

class _EventAdminCard extends StatelessWidget {
  final Map<String, dynamic> event;
  final String status;
  final Color statusColor;
  final bool deleting;
  final VoidCallback onDelete;
  final VoidCallback onView;

  const _EventAdminCard({
    required this.event,
    required this.status,
    required this.statusColor,
    required this.deleting,
    required this.onDelete,
    required this.onView,
  });

  @override
  Widget build(BuildContext context) {
    final compact = MediaQuery.of(context).size.width < 720;
    final title = _text(event['title'], 'Untitled event');
    final description = _text(event['description'], 'No description provided.');
    final image = _firstImageSource(event);

    final content = Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Wrap(
                    spacing: 7,
                    runSpacing: 7,
                    children: [
                      _EventStatusBadge(label: status, color: statusColor),
                      _EventStatusBadge(label: _text(event['category'], 'General'), color: _eventGold),
                    ],
                  ),
                  const SizedBox(height: 10),
                  Text(
                    title,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: const TextStyle(fontSize: 18, height: 1.25, fontWeight: FontWeight.w900, color: _eventText),
                  ),
                ],
              ),
            ),
            const SizedBox(width: 8),
            IconButton(
              tooltip: 'View details',
              onPressed: onView,
              icon: const Icon(Icons.open_in_new_rounded, color: _eventGreen),
            ),
          ],
        ),
        const SizedBox(height: 9),
        Text(
          description,
          maxLines: 3,
          overflow: TextOverflow.ellipsis,
          style: const TextStyle(color: _eventMuted, fontSize: 12.5, height: 1.5),
        ),
        const SizedBox(height: 13),
        Wrap(
          spacing: 12,
          runSpacing: 8,
          children: [
            _EventMeta(icon: Icons.schedule_rounded, text: _formatDate(event['event_date'])),
            _EventMeta(icon: Icons.domain_outlined, text: _text(event['campus'], 'University Wide')),
            _EventMeta(icon: Icons.location_on_outlined, text: _text(event['location'], 'No venue')),
            _EventMeta(icon: Icons.person_outline_rounded, text: _text(event['author_name'], 'Rockview Events')),
          ],
        ),
        const SizedBox(height: 13),
        Container(height: 1, color: _eventBorder),
        const SizedBox(height: 12),
        Row(
          children: [
            _EventMetric(icon: Icons.favorite_border_rounded, value: '${_int(event['like_count'])}'),
            const SizedBox(width: 14),
            _EventMetric(icon: Icons.mode_comment_outlined, value: '${_int(event['comment_count'])}'),
            const SizedBox(width: 14),
            _EventMetric(icon: Icons.perm_media_outlined, value: '${_mediaCount(event)}'),
            const Spacer(),
            deleting
                ? const SizedBox(width: 26, height: 26, child: CircularProgressIndicator(strokeWidth: 2.5, color: Colors.redAccent))
                : OutlinedButton.icon(
                    onPressed: onDelete,
                    style: OutlinedButton.styleFrom(
                      foregroundColor: Colors.redAccent,
                      side: BorderSide(color: Colors.red.shade200),
                      padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 12),
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                    ),
                    icon: const Icon(Icons.delete_outline_rounded, size: 18),
                    label: const Text('DELETE', style: TextStyle(fontWeight: FontWeight.w900, fontSize: 11)),
                  ),
          ],
        ),
      ],
    );

    return Container(
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: _eventBorder),
        boxShadow: const [
          BoxShadow(color: Color(0x07000000), blurRadius: 14, offset: Offset(0, 5)),
        ],
      ),
      child: compact
          ? Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                _EventThumbnail(source: image, height: 180),
                const SizedBox(height: 14),
                content,
              ],
            )
          : Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(width: 220, child: _EventThumbnail(source: image, height: 170)),
                const SizedBox(width: 18),
                Expanded(child: content),
              ],
            ),
    );
  }
}

class _EventThumbnail extends StatelessWidget {
  final String source;
  final double height;

  const _EventThumbnail({required this.source, required this.height});

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(15),
      child: SizedBox(
        height: height,
        child: source.isEmpty ? _fallback() : _image(source),
      ),
    );
  }

  Widget _image(String source) {
    final trimmed = source.trim();
    if (trimmed.startsWith('http://') || trimmed.startsWith('https://') || trimmed.startsWith('uploads/') || trimmed.startsWith('/uploads/')) {
      final url = trimmed.startsWith('http')
          ? trimmed
          : '${ApiClient.baseUrl}/${trimmed.startsWith('/') ? trimmed.substring(1) : trimmed}';
      return Image.network(
        url,
        fit: BoxFit.cover,
        cacheWidth: 900,
        errorBuilder: (_, __, ___) => _fallback(),
      );
    }

    try {
      var clean = trimmed;
      if (clean.contains(',')) clean = clean.split(',').last;
      clean = clean.replaceAll(RegExp(r'\s+'), '');
      return Image.memory(
        base64Decode(clean),
        fit: BoxFit.cover,
        gaplessPlayback: true,
        errorBuilder: (_, __, ___) => _fallback(),
      );
    } catch (_) {
      return _fallback();
    }
  }

  Widget _fallback() {
    return Container(
      color: const Color(0xFFF0F4F1),
      child: const Center(
        child: Icon(Icons.event_available_outlined, size: 54, color: Color(0xFFB1BDB6)),
      ),
    );
  }
}

class _EventStatusBadge extends StatelessWidget {
  final String label;
  final Color color;

  const _EventStatusBadge({required this.label, required this.color});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5),
      decoration: BoxDecoration(
        color: color.withOpacity(.08),
        borderRadius: BorderRadius.circular(999),
        border: Border.all(color: color.withOpacity(.22)),
      ),
      child: Text(
        label.toUpperCase(),
        style: TextStyle(color: color, fontSize: 9.5, fontWeight: FontWeight.w900, letterSpacing: .6),
      ),
    );
  }
}

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

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

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(icon, size: 15, color: _eventMuted),
        const SizedBox(width: 5),
        ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 240),
          child: Text(text, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _eventMuted, fontSize: 11.5, fontWeight: FontWeight.w600)),
        ),
      ],
    );
  }
}

class _EventMetric extends StatelessWidget {
  final IconData icon;
  final String value;

  const _EventMetric({required this.icon, required this.value});

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(icon, size: 17, color: _eventMuted),
        const SizedBox(width: 5),
        Text(value, style: const TextStyle(color: _eventText, fontWeight: FontWeight.w800, fontSize: 11.5)),
      ],
    );
  }
}

class _EventStatData {
  final String label;
  final int value;
  final IconData icon;
  final Color color;

  const _EventStatData(this.label, this.value, this.icon, this.color);
}

class _EventStatCard extends StatelessWidget {
  final _EventStatData data;

  const _EventStatCard({required this.data});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(17),
        border: Border.all(color: _eventBorder),
      ),
      child: Row(
        children: [
          Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(color: data.color.withOpacity(.08), borderRadius: BorderRadius.circular(12)),
            child: Icon(data.icon, color: data.color, size: 21),
          ),
          const SizedBox(width: 11),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('${data.value}', style: const TextStyle(fontSize: 19, fontWeight: FontWeight.w900, color: _eventText)),
                const SizedBox(height: 2),
                Text(data.label, style: const TextStyle(color: _eventMuted, fontSize: 10.5, fontWeight: FontWeight.w700)),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

String _firstImageSource(Map<String, dynamic> event) {
  final media = event['media'];
  if (media is List) {
    for (final raw in media) {
      if (raw is! Map) continue;
      final type = _text(raw['type'] ?? raw['media_type']).toLowerCase();
      if (type == 'video') continue;
      final thumb = _text(raw['thumbnail_path'] ?? raw['thumbnail']);
      if (thumb.isNotEmpty) return thumb;
      final path = _text(raw['path'] ?? raw['media_path']);
      if (path.isNotEmpty) return path;
    }
  }
  return _text(event['image_url']);
}

int _mediaCount(Map<String, dynamic> event) {
  final media = event['media'];
  if (media is List) return media.length;
  return _text(event['image_url']).isEmpty ? 0 : 1;
}

String _formatDate(dynamic value) {
  final date = _parseDate(value);
  if (date == null) return 'Date not set';
  final local = date.toLocal();
  const months = <String>[
    'Jan',
    'Feb',
    'Mar',
    'Apr',
    'May',
    'Jun',
    'Jul',
    'Aug',
    'Sep',
    'Oct',
    'Nov',
    'Dec',
  ];
  final hour = local.hour == 0 ? 12 : (local.hour > 12 ? local.hour - 12 : local.hour);
  final minute = local.minute.toString().padLeft(2, '0');
  final ampm = local.hour >= 12 ? 'PM' : 'AM';
  return '${local.day} ${months[local.month - 1]} ${local.year} • $hour:$minute $ampm';
}

DateTime? _parseDate(dynamic value) {
  final text = _text(value);
  if (text.isEmpty) return null;
  return DateTime.tryParse(text);
}

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

int _int(dynamic value) => int.tryParse('${value ?? ''}') ?? 0;

bool _bool(dynamic value) {
  if (value is bool) return value;
  if (value is num) return value != 0;
  return const {'1', 'true', 't', 'yes', 'y'}.contains(value?.toString().trim().toLowerCase());
}

String _responseMessage(http.Response response, String fallback) {
  try {
    final decoded = jsonDecode(response.body);
    if (decoded is Map) {
      final message = _text(decoded['detail'] ?? decoded['message'] ?? decoded['error']);
      if (message.isNotEmpty) return message;
    }
  } catch (_) {}
  return '$fallback (HTTP ${response.statusCode})';
}

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