// lib/features/student/tabs/view_announcements_tab.dart

import 'package:flutter/material.dart';
// Note: Update this import if students use a different API client to fetch announcements
import '../../../../core/networks/api_admin.dart';

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

  @override
  State<ViewAnnouncementsTab> createState() => _ViewAnnouncementsTabState();
}

class _ViewAnnouncementsTabState extends State<ViewAnnouncementsTab> {
  // Standard Color Palette
  static const Color _brandBlue = Color.fromARGB(255, 12, 53, 106);
  static const Color _brandGreen = Color.fromARGB(255, 16, 116, 41);
  static const Color _surfaceBg = Color(0xFFF8F9FA);

  bool _isLoadingHistory = true;
  List<dynamic> _allAnnouncements = [];

  // Filtering State
  String _selectedCampus = 'All Campuses';
  final List<String> _campuses = [
    'All Campuses',
    'Main Campus',
    'Ndola Campus',
    'Lusaka Campus',
    'City Campus',
  ];

  String _selectedCategory = 'All Categories';
  final List<String> _categories = [
    'All Categories',
    'General',
    'Academic',
    'Events',
    'Urgent',
    'Maintenance',
  ];

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

  Future<void> _fetchAnnouncementsHistory() async {
    setState(() => _isLoadingHistory = true);
    try {
      final data = await ApiAdmin.getAnnouncements();
      if (mounted) {
        setState(() {
          if (data is List) {
            _allAnnouncements = List.from(data);
          } else {
            _allAnnouncements = [];
          }
          _isLoadingHistory = false;
        });
      }
    } catch (e) {
      debugPrint("Error fetching announcements: $e");
      if (mounted) {
        setState(() {
          _isLoadingHistory = false;
          _allAnnouncements = [];
        });
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Failed to load announcements.'),
            backgroundColor: Colors.redAccent,
          ),
        );
      }
    }
  }

  // Helper to filter and sort announcements
  List<dynamic> get _displayedAnnouncements {
    List<dynamic> filtered = _allAnnouncements.where((item) {
      final matchesCampus = _selectedCampus == 'All Campuses' || 
          item['campus'] == 'All' || 
          item['campus'] == _selectedCampus;
          
      final matchesCategory = _selectedCategory == 'All Categories' || 
          item['category'] == _selectedCategory;
          
      return matchesCampus && matchesCategory;
    }).toList();

    // Sort: Pinned first, then standard (assuming recent is first from backend)
    filtered.sort((a, b) {
      final bool aPinned = a['is_pinned'] == true || a['is_pinned'] == 1;
      final bool bPinned = b['is_pinned'] == true || b['is_pinned'] == 1;
      if (aPinned && !bPinned) return -1;
      if (!aPinned && bPinned) return 1;
      return 0; // Maintain original chronological order
    });

    return filtered;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: _surfaceBg,
      child: LayoutBuilder(
        builder: (context, constraints) {
          final bool isDesktop = constraints.maxWidth > 950;

          return Padding(
            padding: EdgeInsets.all(isDesktop ? 32.0 : 16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // --- HEADER TEXT ---
                const Text(
                  'University Notice Board',
                  style: TextStyle(
                    fontSize: 32,
                    fontWeight: FontWeight.w900,
                    color: Color(0xFF1A1F36),
                    letterSpacing: -0.5,
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  'Stay updated with the latest news, academic updates, and urgent notices.',
                  style: TextStyle(fontSize: 16, color: Colors.grey.shade600, fontWeight: FontWeight.w500),
                ),
                const SizedBox(height: 32),

                // --- TWO PANEL LAYOUT ---
                Expanded(
                  child: isDesktop
                      ? Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Expanded(
                              flex: 3,
                              child: _buildSidebarFilters(),
                            ),
                            const SizedBox(width: 32),
                            Expanded(
                              flex: 7,
                              child: _buildAnnouncementsFeed(),
                            ),
                          ],
                        )
                      : Column(
                          children: [
                            _buildMobileFilters(),
                            const SizedBox(height: 20),
                            Expanded(child: _buildAnnouncementsFeed()),
                          ],
                        ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  // ============================================================================
  // SIDEBAR FILTERS (DESKTOP)
  // ============================================================================
  Widget _buildSidebarFilters() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: Colors.grey.shade200),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.03),
            blurRadius: 24,
            offset: const Offset(0, 8),
          ),
        ],
      ),
      // CRITICAL FIX: Wrapped in SingleChildScrollView to prevent RenderFlex overflow
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(28),
        physics: const BouncingScrollPhysics(),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(Icons.tune_rounded, color: Colors.grey.shade800, size: 22),
                const SizedBox(width: 12),
                const Text(
                  'Filter Notices',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.w800, color: Color(0xFF1A1F36)),
                ),
              ],
            ),
            const SizedBox(height: 32),
            
            // Campus Filter
            Text('CAMPUS', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12, letterSpacing: 1.2, color: Colors.grey.shade500)),
            const SizedBox(height: 12),
            ..._campuses.map((campus) => _buildCustomSidebarTile(
              title: campus,
              isSelected: _selectedCampus == campus,
              activeColor: _brandBlue,
              onTap: () => setState(() => _selectedCampus = campus),
            )),
            
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 24.0),
              child: Divider(color: Colors.grey.shade100, thickness: 2),
            ),

            // Category Filter
            Text('CATEGORY', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12, letterSpacing: 1.2, color: Colors.grey.shade500)),
            const SizedBox(height: 12),
            ..._categories.map((category) => _buildCustomSidebarTile(
              title: category,
              isSelected: _selectedCategory == category,
              activeColor: _brandGreen,
              onTap: () => setState(() => _selectedCategory = category),
            )),
          ],
        ),
      ),
    );
  }

  Widget _buildCustomSidebarTile({required String title, required bool isSelected, required Color activeColor, required VoidCallback onTap}) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8.0),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(12),
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 200),
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
          decoration: BoxDecoration(
            color: isSelected ? activeColor.withOpacity(0.08) : Colors.transparent,
            borderRadius: BorderRadius.circular(12),
            border: Border.all(
              color: isSelected ? activeColor.withOpacity(0.3) : Colors.transparent,
            )
          ),
          child: Row(
            children: [
              AnimatedContainer(
                duration: const Duration(milliseconds: 200),
                width: 18,
                height: 18,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  border: Border.all(color: isSelected ? activeColor : Colors.grey.shade400, width: isSelected ? 5 : 2),
                ),
              ),
              const SizedBox(width: 16),
              Text(
                title,
                style: TextStyle(
                  fontSize: 15,
                  fontWeight: isSelected ? FontWeight.bold : FontWeight.w500,
                  color: isSelected ? activeColor : Colors.grey.shade700,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // ============================================================================
  // MOBILE FILTERS (HORIZONTAL SCROLL)
  // ============================================================================
  Widget _buildMobileFilters() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        _buildHorizontalFilterRow(
          items: _campuses,
          selectedValue: _selectedCampus,
          activeColor: _brandBlue,
          onSelected: (val) => setState(() => _selectedCampus = val),
        ),
        const SizedBox(height: 12),
        _buildHorizontalFilterRow(
          items: _categories,
          selectedValue: _selectedCategory,
          activeColor: _brandGreen,
          onSelected: (val) => setState(() => _selectedCategory = val),
        ),
      ],
    );
  }

  Widget _buildHorizontalFilterRow({required List<String> items, required String selectedValue, required Color activeColor, required Function(String) onSelected}) {
    return SizedBox(
      height: 44,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        physics: const BouncingScrollPhysics(),
        itemCount: items.length,
        itemBuilder: (context, index) {
          final item = items[index];
          final isSelected = item == selectedValue;
          return Padding(
            padding: const EdgeInsets.only(right: 12.0),
            child: InkWell(
              onTap: () => onSelected(item),
              borderRadius: BorderRadius.circular(24),
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 200),
                padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 0),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: isSelected ? activeColor : Colors.white,
                  borderRadius: BorderRadius.circular(24),
                  border: Border.all(color: isSelected ? activeColor : Colors.grey.shade300),
                  boxShadow: isSelected ? [BoxShadow(color: activeColor.withOpacity(0.3), blurRadius: 8, offset: const Offset(0, 4))] : [],
                ),
                child: Text(
                  item,
                  style: TextStyle(
                    color: isSelected ? Colors.white : Colors.grey.shade700,
                    fontWeight: isSelected ? FontWeight.bold : FontWeight.w600,
                    fontSize: 14,
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  // ============================================================================
  // ANNOUNCEMENTS FEED
  // ============================================================================
  Widget _buildAnnouncementsFeed() {
    if (_isLoadingHistory) {
      return const Center(child: CircularProgressIndicator(color: _brandBlue));
    }

    final displayed = _displayedAnnouncements;

    if (displayed.isEmpty) {
      return Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(20),
          border: Border.all(color: Colors.grey.shade200),
        ),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                padding: const EdgeInsets.all(24),
                decoration: BoxDecoration(color: Colors.grey.shade50, shape: BoxShape.circle),
                child: Icon(Icons.campaign_outlined, size: 64, color: Colors.grey.shade400),
              ),
              const SizedBox(height: 24),
              Text(
                "No announcements found.",
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.w800, color: Colors.grey.shade800),
              ),
              const SizedBox(height: 8),
              Text('Check back later or adjust your filters.', style: TextStyle(color: Colors.grey.shade500, fontSize: 15)),
            ],
          ),
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: _fetchAnnouncementsHistory,
      color: _brandBlue,
      backgroundColor: Colors.white,
      child: ListView.separated(
        physics: const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()),
        padding: const EdgeInsets.only(bottom: 32, right: 8),
        itemCount: displayed.length,
        separatorBuilder: (context, index) => const SizedBox(height: 20),
        itemBuilder: (context, index) {
          return _AnnouncementCard(item: displayed[index]);
        },
      ),
    );
  }
}

// ============================================================================
// CUSTOM CARD FOR ANNOUNCEMENTS (Premium & Professional)
// ============================================================================
class _AnnouncementCard extends StatefulWidget {
  final Map<String, dynamic> item;

  const _AnnouncementCard({required this.item});

  @override
  State<_AnnouncementCard> createState() => _AnnouncementCardState();
}

class _AnnouncementCardState extends State<_AnnouncementCard> {
  bool _isExpanded = false;
  final int _wordLimit = 40; 

  Color _getCategoryColor(String category) {
    switch (category.toLowerCase()) {
      case 'urgent':
        return const Color(0xFFE53935); // Sleeker Red
      case 'academic':
        return const Color.fromARGB(255, 12, 53, 106); // Brand Blue
      case 'events':
        return const Color.fromARGB(255, 16, 116, 41); // Brand Green
      case 'maintenance':
        return const Color(0xFFF57C00); // Sleeker Orange
      default:
        return const Color(0xFF546E7A); // Blue Grey
    }
  }

  IconData _getCategoryIcon(String category) {
    switch (category.toLowerCase()) {
      case 'urgent':
        return Icons.campaign_rounded;
      case 'academic':
        return Icons.school_rounded;
      case 'events':
        return Icons.event_rounded;
      case 'maintenance':
        return Icons.engineering_rounded;
      default:
        return Icons.feed_rounded;
    }
  }

  @override
  Widget build(BuildContext context) {
    final item = widget.item;
    final String title = item['title'] ?? 'Untitled Notice';
    final String campus = item['campus'] == 'All' ? 'All Campuses' : (item['campus'] ?? 'General');
    final String author = item['author_name'] ?? 'University Admin';
    final String category = item['category'] ?? 'General';
    final bool isPinned = item['is_pinned'] == true || item['is_pinned'] == 1;

    final Color categoryColor = _getCategoryColor(category);
    final IconData categoryIcon = _getCategoryIcon(category);

    final String rawDate = item['created_at'] ?? '';
    String displayDate = 'Recently';
    if (rawDate.isNotEmpty) {
      try {
        final dt = DateTime.parse(rawDate).toLocal();
        const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
        displayDate = "${months[dt.month - 1]} ${dt.day}, ${dt.year}";
      } catch (_) {}
    }

    final String rawContent = item['content'] ?? 'No content provided.';
    final List<String> words = rawContent.split(RegExp(r'\s+'));
    final bool isLongText = words.length > _wordLimit;

    String displayText = rawContent;
    if (isLongText && !_isExpanded) {
      displayText = '${words.take(_wordLimit).join(' ')}...';
    }

    return Container(
      decoration: BoxDecoration(
        color: isPinned ? Colors.amber.shade50.withOpacity(0.4) : Colors.white,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: isPinned ? Colors.amber.shade300 : Colors.grey.shade200, width: isPinned ? 2 : 1),
        boxShadow: [
          BoxShadow(
            color: isPinned ? Colors.amber.withOpacity(0.1) : Colors.black.withOpacity(0.03),
            blurRadius: 20,
            offset: const Offset(0, 8),
          ),
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(20),
        child: IntrinsicHeight(
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              // Left Color Indicator Bar
              Container(
                width: 6,
                color: isPinned ? Colors.amber.shade600 : categoryColor,
              ),
              
              // Main Card Content
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.all(28.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // Meta Row
                      Row(
                        children: [
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                            decoration: BoxDecoration(
                              color: categoryColor.withOpacity(0.1),
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Icon(categoryIcon, size: 16, color: categoryColor),
                                const SizedBox(width: 6),
                                Text(
                                  category.toUpperCase(),
                                  style: TextStyle(color: categoryColor, fontSize: 12, fontWeight: FontWeight.w800, letterSpacing: 0.8),
                                ),
                              ],
                            ),
                          ),
                          const SizedBox(width: 16),
                          Text(
                            displayDate,
                            style: TextStyle(color: Colors.grey.shade500, fontSize: 13, fontWeight: FontWeight.w600),
                          ),
                          const Spacer(),
                          if (isPinned)
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                              decoration: BoxDecoration(
                                color: Colors.amber.shade100,
                                borderRadius: BorderRadius.circular(20),
                              ),
                              child: Row(
                                children: [
                                  Icon(Icons.push_pin_rounded, size: 12, color: Colors.amber.shade900),
                                  const SizedBox(width: 4),
                                  Text('PINNED', style: TextStyle(fontSize: 11, fontWeight: FontWeight.w800, letterSpacing: 0.5, color: Colors.amber.shade900)),
                                ],
                              ),
                            ),
                        ],
                      ),
                      const SizedBox(height: 20),
                      
                      // Title
                      Text(
                        title,
                        style: const TextStyle(fontSize: 22, fontWeight: FontWeight.w900, color: Color(0xFF1A1F36), height: 1.3, letterSpacing: -0.3),
                      ),
                      const SizedBox(height: 12),
                      
                      // Content Body
                      AnimatedSize(
                        duration: const Duration(milliseconds: 300),
                        curve: Curves.easeInOut,
                        child: SelectableText(
                          displayText,
                          style: TextStyle(fontSize: 16, color: Colors.grey.shade800, height: 1.6),
                        ),
                      ),
                      
                      // Read More Button
                      if (isLongText)
                        Padding(
                          padding: const EdgeInsets.only(top: 16.0),
                          child: InkWell(
                            onTap: () => setState(() => _isExpanded = !_isExpanded),
                            borderRadius: BorderRadius.circular(6),
                            child: Padding(
                              padding: const EdgeInsets.symmetric(vertical: 4.0, horizontal: 2.0),
                              child: Text(
                                _isExpanded ? 'Show less' : 'Read full announcement...',
                                style: TextStyle(
                                  color: categoryColor, 
                                  fontWeight: FontWeight.w800, 
                                  fontSize: 15,
                                  decoration: TextDecoration.underline,
                                  decorationColor: categoryColor.withOpacity(0.5)
                                ),
                              ),
                            ),
                          ),
                        ),
                      
                      const SizedBox(height: 24),
                      Divider(color: Colors.grey.shade200, height: 1),
                      const SizedBox(height: 16),
                      
                      // Footer (Author & Campus)
                      Row(
                        children: [
                          CircleAvatar(
                            radius: 16,
                            backgroundColor: Colors.grey.shade100,
                            child: Text(
                              author.isNotEmpty ? author[0].toUpperCase() : 'U',
                              style: TextStyle(color: Colors.grey.shade700, fontWeight: FontWeight.bold, fontSize: 13),
                            ),
                          ),
                          const SizedBox(width: 12),
                          Text(
                            author,
                            style: const TextStyle(fontWeight: FontWeight.w700, fontSize: 14, color: Color(0xFF1A1F36)),
                          ),
                          const Spacer(),
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
                            decoration: BoxDecoration(
                              color: Colors.grey.shade50,
                              borderRadius: BorderRadius.circular(8),
                              border: Border.all(color: Colors.grey.shade200)
                            ),
                            child: Row(
                              children: [
                                Icon(Icons.location_on_rounded, size: 14, color: Colors.grey.shade500),
                                const SizedBox(width: 6),
                                Text(
                                  campus,
                                  style: TextStyle(color: Colors.grey.shade700, fontSize: 13, fontWeight: FontWeight.w600),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}