// D:\Nextjs\latest-deployed-universitiespage-code\src\app\admin\news\list\page.js

'use client';

import { useState, useEffect } from 'react';
import { Pencil, Trash2, User, ExternalLink, Plus } from 'lucide-react';
import { useRouter } from 'next/navigation';
import Pagination from '../../components/Pagination';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || '';

export default function NewsList() {
  const [news, setNews] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedNewsId, setSelectedNewsId] = useState(null);
  const [comments, setComments] = useState([]);
  const [commentLoading, setCommentLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalItems, setTotalItems] = useState(0);
  const [totalPages, setTotalPages] = useState(1);
  const itemsPerPage = 15;
  
  // Filter states
  const [searchTerm, setSearchTerm] = useState("");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [popularFilter, setPopularFilter] = useState("");
  const [activeFilter, setActiveFilter] = useState("");
  const [authorFilter, setAuthorFilter] = useState("");
  const [authors, setAuthors] = useState([]); // For author dropdown
  
  // Applied filters state
  const [appliedSearchTerm, setAppliedSearchTerm] = useState("");
  const [appliedStartDate, setAppliedStartDate] = useState("");
  const [appliedEndDate, setAppliedEndDate] = useState("");
  const [appliedPopularFilter, setAppliedPopularFilter] = useState("");
  const [appliedActiveFilter, setAppliedActiveFilter] = useState("");
  const [appliedAuthorFilter, setAppliedAuthorFilter] = useState("");
  
  const [isFilterOpen, setIsFilterOpen] = useState(false);

  const router = useRouter();

  // Load authors for filter dropdown
  const loadAuthors = async () => {
    try {
      const res = await fetch('/api/internal/authors?status=active');
      const data = await res.json();
      
      if (data.success) {
        setAuthors(data.data);
      }
    } catch (error) {
      console.error('Error loading authors:', error);
    }
  };

  const fetchNews = async (page = 1) => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: page.toString(),
        limit: itemsPerPage.toString()
      });
      
      if (appliedSearchTerm) {
        params.append('search', appliedSearchTerm);
      }
      if (appliedStartDate) {
        params.append('start_date', appliedStartDate);
      }
      if (appliedEndDate) {
        params.append('end_date', appliedEndDate);
      }
      if (appliedPopularFilter !== '') {
        params.append('popular', appliedPopularFilter);
      }
      if (appliedActiveFilter !== '') {
        params.append('active', appliedActiveFilter);
      }
      if (appliedAuthorFilter) {
        params.append('author', appliedAuthorFilter);
      }

      const apiUrl = `/api/internal/news?${params.toString()}`;
      console.log('🔍 Fetching news with params:', params.toString());

      const res = await fetch(apiUrl);
      
      if (!res.ok) {
        const errorText = await res.text();
        throw new Error(`API Error: ${res.status} - ${errorText}`);
      }
      
      const data = await res.json();
      
      if (data.success) {
        const newsWithMeta = data.data?.map(newsItem => ({
          ...newsItem,
          enable_meta_tags: newsItem.enable_meta_tags || false
        })) || [];
        
        setNews(newsWithMeta);
        
        if (data.pagination) {
          setTotalItems(data.pagination.totalItems || newsWithMeta.length);
          setTotalPages(data.pagination.totalPages || Math.ceil(newsWithMeta.length / itemsPerPage));
        } else {
          setTotalItems(newsWithMeta.length);
          setTotalPages(Math.ceil(newsWithMeta.length / itemsPerPage));
        }
      } else {
        console.warn('API returned success: false:', data);
        const items = Array.isArray(data) ? data : data.data;
        if (items) {
          const newsWithMeta = items.map(newsItem => ({
            ...newsItem,
            enable_meta_tags: newsItem.enable_meta_tags || false
          }));
          setNews(newsWithMeta);
          setTotalItems(newsWithMeta.length);
          setTotalPages(Math.ceil(newsWithMeta.length / itemsPerPage));
        } else {
          setNews([]);
          setTotalItems(0);
          setTotalPages(1);
        }
      }
    } catch (error) {
      console.error('Error fetching news:', error);
      setNews([]);
      setTotalItems(0);
      setTotalPages(1);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadAuthors();
    fetchNews(currentPage);
  }, [currentPage, appliedSearchTerm, appliedStartDate, appliedEndDate, appliedPopularFilter, appliedActiveFilter, appliedAuthorFilter]);

  const handleSearch = () => {
    setAppliedSearchTerm(searchTerm);
    setAppliedStartDate(startDate);
    setAppliedEndDate(endDate);
    setAppliedPopularFilter(popularFilter);
    setAppliedActiveFilter(activeFilter);
    setAppliedAuthorFilter(authorFilter);
    setCurrentPage(1);
  };

  const clearFilters = () => {
    setSearchTerm('');
    setStartDate('');
    setEndDate('');
    setPopularFilter('');
    setActiveFilter('');
    setAuthorFilter('');
    setAppliedSearchTerm('');
    setAppliedStartDate('');
    setAppliedEndDate('');
    setAppliedPopularFilter('');
    setAppliedActiveFilter('');
    setAppliedAuthorFilter('');
    setCurrentPage(1);
  };

  const hasActiveFilters = appliedSearchTerm || appliedStartDate || appliedEndDate || appliedPopularFilter !== '' || appliedActiveFilter !== '' || appliedAuthorFilter !== '';

  // Format date for display
  const formatDate = (dateString) => {
    if (!dateString) return 'N/A';
    try {
      const date = new Date(dateString);
      return date.toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
      });
    } catch (e) {
      return 'N/A';
    }
  };

  // Get author name by ID
  const getAuthorName = (authorId) => {
    if (!authorId) return 'No Author';
    const author = authors.find(a => a.id == authorId);
    return author ? author.full_name : `Author ID: ${authorId}`;
  };

  const handleDelete = async (id) => {
    if (!confirm('Are you sure you want to delete this news?')) return;
    try {
      const res = await fetch(`/api/internal/news/${id}`, { method: 'DELETE' });
      if (!res.ok) throw new Error('Failed to delete');
      
      setNews(prev => prev.filter(newsItem => newsItem.id !== id));
      alert('News deleted successfully');
    } catch (err) {
      console.error('Delete error:', err);
      alert('Failed to delete news');
    }
  };

  const toggleFeaturedStatus = async (id, currentStatus) => {
    try {
      const res = await fetch(`/api/internal/news/toggleFeatured/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ is_featured: !currentStatus })
      });

      if (!res.ok) {
        const errorData = await res.json();
        throw new Error(errorData.message || 'Update failed');
      }

      setNews(prev => prev.map(newsItem => 
        newsItem.id === id 
          ? { ...newsItem, is_featured: !currentStatus } 
          : newsItem
      ));
    } catch (err) {
      console.error('Toggle error:', err);
      alert(err.message || 'Error updating status');
    }
  };

  const toggleActiveStatus = async (id, currentStatus) => {
    try {
      const res = await fetch(`/api/internal/news/toggleActive/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ is_active: !currentStatus })
      });

      if (!res.ok) {
        const errorData = await res.json();
        throw new Error(errorData.message || 'Update failed');
      }

      setNews(prev => prev.map(newsItem => 
        newsItem.id === id 
          ? { ...newsItem, is_active: !currentStatus } 
          : newsItem
      ));
    } catch (err) {
      console.error('Toggle error:', err);
      alert(err.message || 'Error updating status');
    }
  };

  const handleEdit = (id) => {
    router.push(`/admin/news/edit/${id}`);
  };

  // Function to assign/change author
  const handleAssignAuthor = async (newsId, currentAuthorId) => {
    try {
      // Create a modal or dropdown for author selection
      const selectedAuthorId = prompt(
        'Enter Author ID to assign (or leave empty to remove author):\n' +
        'Available Authors:\n' +
        authors.map(a => `${a.id}: ${a.full_name}`).join('\n'),
        currentAuthorId || ''
      );

      if (selectedAuthorId === null) return; // User cancelled

      const authorId = selectedAuthorId.trim() || null;

      // Validate author ID if provided
      if (authorId && !authors.find(a => a.id == authorId)) {
        alert('Invalid Author ID');
        return;
      }

      // Update the news with new author
      const res = await fetch(`/api/internal/news/${newsId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ author_id: authorId })
      });

      if (!res.ok) {
        throw new Error('Failed to update author');
      }

      // Update local state
      setNews(prev => prev.map(newsItem => 
        newsItem.id === newsId 
          ? { 
              ...newsItem, 
              author_id: authorId,
              author_name: authorId ? authors.find(a => a.id == authorId)?.full_name : null,
              author_image: authorId ? authors.find(a => a.id == authorId)?.profile_image : null
            } 
          : newsItem
      ));

      alert('Author updated successfully');
    } catch (err) {
      console.error('Assign author error:', err);
      alert('Failed to update author');
    }
  };

  const fetchComments = async (newsId) => {
    setCommentLoading(true);
    setSelectedNewsId(newsId);
    try {
      const res = await fetch(`/api/internal/comments?news_id=${newsId}`);
      const data = await res.json();
      if (data.success) {
        setComments(data.data);
      }
    } catch (err) {
      console.error('Error loading comments:', err);
    } finally {
      setCommentLoading(false);
    }
  };

  const closeModal = () => {
    setSelectedNewsId(null);
    setComments([]);
  };

  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + news.length;

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      <div className="bg-white rounded-2xl shadow-lg p-6">
        {/* Header */}
        <div className="flex flex-col md:flex-row justify-between md:items-center gap-4 mb-6 sm:mb-8">
          <div>
            <h1 className="text-3xl font-bold text-gray-800 mb-1">News List</h1>
            <p className="text-gray-600 text-sm sm:text-base">Manage and organize your news</p>
          </div>
          <div className="flex gap-3">
            <button
              onClick={() => setIsFilterOpen(!isFilterOpen)}
              className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors flex items-center gap-2"
            >
              🔍 Filters {hasActiveFilters && `(${hasActiveFilters})`}
            </button>
            <button
              onClick={() => router.push('/admin/authors')}
              className="px-4 py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition-colors flex items-center gap-2"
            >
              <User size={16} />
              Manage Authors
            </button>
            <button
              onClick={() => router.push('/admin/news/add')}
              className="px-4 py-2 bg-linear-to-b from-[#0B6D76] to-[#094F56] text-white rounded-md flex items-center gap-2"
            >
              <Plus size={16} />
              Create News
            </button>
          </div>
        </div>

        {/* Filter Section */}
        {isFilterOpen && (
          <div className="bg-gray-50 rounded-lg p-4 mb-6">
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Search News</label>
                <input
                  type="text"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                  placeholder="Search by title, content, author..."
                  className="w-full p-2 border rounded"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Start Date</label>
                <input
                  type="date"
                  value={startDate}
                  onChange={(e) => setStartDate(e.target.value)}
                  className="w-full p-2 border rounded"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">End Date</label>
                <input
                  type="date"
                  value={endDate}
                  onChange={(e) => setEndDate(e.target.value)}
                  className="w-full p-2 border rounded"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Written By (Author)</label>
                <select
                  value={authorFilter}
                  onChange={(e) => setAuthorFilter(e.target.value)}
                  className="w-full p-2 border rounded"
                >
                  <option value="">All Authors</option>
                  {authors.map((author) => (
                    <option key={author.id} value={author.id}>
                      {author.full_name}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Featured</label>
                <select
                  value={popularFilter}
                  onChange={(e) => setPopularFilter(e.target.value)}
                  className="w-full p-2 border rounded"
                >
                  <option value="">All</option>
                  <option value="true">Featured</option>
                  <option value="false">Not Featured</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Active</label>
                <select
                  value={activeFilter}
                  onChange={(e) => setActiveFilter(e.target.value)}
                  className="w-full p-2 border rounded"
                >
                  <option value="">All</option>
                  <option value="true">Active</option>
                  <option value="false">Inactive</option>
                </select>
              </div>
              <div className="flex items-end gap-2 sm:col-span-2 lg:col-span-6">
                <button 
                  onClick={handleSearch} 
                  className="px-4 py-2 bg-linear-to-b from-[#0B6D76] to-[#094F56] text-white rounded hover:from-[#094F56] hover:to-[#083a40] flex items-center gap-2 transition-all"
                >
                  🔍 Search
                </button>
                <button 
                  onClick={clearFilters} 
                  className="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600 transition-colors"
                >
                  Clear Filters
                </button>
              </div>
            </div>

            {/* Active Filters Display */}
            {(appliedSearchTerm || appliedStartDate || appliedEndDate || appliedPopularFilter !== '' || appliedActiveFilter !== '' || appliedAuthorFilter !== '') && (
              <div className="mt-4 pt-4 border-t border-gray-200">
                <div className="text-sm text-gray-600 flex flex-wrap gap-2">
                  Active filters: 
                  {appliedSearchTerm && <span className="px-2 py-1 bg-blue-100 text-blue-800 rounded">Search: "{appliedSearchTerm}"</span>}
                  {appliedStartDate && <span className="px-2 py-1 bg-orange-100 text-orange-800 rounded">From: {formatDate(appliedStartDate)}</span>}
                  {appliedEndDate && <span className="px-2 py-1 bg-yellow-100 text-yellow-800 rounded">To: {formatDate(appliedEndDate)}</span>}
                  {appliedAuthorFilter && (
                    <span className="px-2 py-1 bg-purple-100 text-purple-800 rounded">
                      Author: {getAuthorName(appliedAuthorFilter)}
                    </span>
                  )}
                  {appliedPopularFilter !== '' && <span className="px-2 py-1 bg-pink-100 text-pink-800 rounded">Featured: {appliedPopularFilter === 'true' ? 'Yes' : 'No'}</span>}
                  {appliedActiveFilter !== '' && <span className="px-2 py-1 bg-green-100 text-green-800 rounded">Active: {appliedActiveFilter === 'true' ? 'Yes' : 'No'}</span>}
                </div>
              </div>
            )}
          </div>
        )}

        <div className="overflow-x-auto">
          <table className="min-w-full">
            <thead className="bg-gray-100">
              <tr>
                <th className="py-3 px-4 text-left text-sm font-semibold text-gray-600">Image</th>
                <th className="py-3 px-4 text-left text-sm font-semibold text-gray-600">Title</th>
                <th className="py-3 px-4 text-left text-sm font-semibold text-gray-600">Created By</th>
                <th className="py-3 px-4 text-left text-sm font-semibold text-gray-600">Written By</th>
                <th className="py-3 px-4 text-center text-sm font-semibold text-gray-600">Featured</th>
                <th className="py-3 px-4 text-center text-sm font-semibold text-gray-600">Active</th>
                <th className="py-3 px-4 text-left text-sm font-semibold text-gray-600">Created At</th>
                <th className="py-3 px-4 text-center text-sm font-semibold text-gray-600">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {loading ? (
                <tr>
                  <td colSpan={9} className="text-center py-12 text-gray-500 text-lg">
                    <div className="flex justify-center">
                      <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#0B6D76]"></div>
                    </div>
                  </td>
                </tr>
              ) : news.length === 0 ? (
                <tr>
                  <td colSpan={9} className="text-center py-12 text-gray-500 text-lg">
                    {hasActiveFilters ? 'No news found matching your filters.' : 'No news found. Create your first news!'}
                  </td>
                </tr>
              ) : (
                news.map((newsItem) => {
                  const imageUrl = newsItem.image?.startsWith('http') 
                    ? newsItem.image 
                    : newsItem.image?.startsWith('/') 
                      ? `${API_BASE_URL}${newsItem.image}` 
                      : newsItem.image
                        ? `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${newsItem.image}`
                        : null;

                  return (
                    <tr key={newsItem.id} className="hover:bg-gray-50">
                      <td className="py-3 px-4">
                        {imageUrl ? (
                          <img
                            src={imageUrl}
                            alt={newsItem.title}
                            className="w-16 h-16 object-cover rounded-lg border border-gray-200"
                          />
                        ) : (
                          <div className="w-16 h-16 bg-linear-to-br from-gray-100 to-gray-200 rounded-lg flex items-center justify-center text-gray-400 text-sm border border-gray-200">
                            No Image
                          </div>
                        )}
                      </td>
                      <td className="py-3 px-4 font-medium text-gray-800">
                        <div className="flex flex-col">
                          <a 
                            href={`/news/${newsItem.slug}`} 
                            target='_blank' 
                            rel="noopener noreferrer" 
                            className="hover:text-[#0B6D76] transition-colors flex items-center gap-1"
                          >
                            {newsItem.title}
                            <ExternalLink size={14} className="opacity-70" />
                          </a>
                          {newsItem.description && (
                            <div className="text-xs text-gray-500 mt-1 truncate max-w-xs">
                              {newsItem.description.replace(/<[^>]*>/g, '').substring(0, 60)}...
                            </div>
                          )}
                        </div>
                      </td>
                      
                      {/* Created By Column - Who added the content */}
                      <td className="py-3 px-4">
                        <div className="flex items-center gap-3">
                          <div className="w-10 h-10 rounded-full bg-linear-to-b from-gray-100 to-gray-200 flex items-center justify-center border border-gray-300">
                            <User size={16} className="text-gray-500" />
                          </div>
                          <div>
                            <div className="font-medium text-gray-800">
                              {newsItem.user_name || `User ${newsItem.user_id}`}
                            </div>
                            <div className="text-xs text-gray-500">
                              User ID: {newsItem.user_id}
                            </div>
                          </div>
                        </div>
                      </td>
                      
                      {/* Written By Column - Author who wrote the content */}
                      <td className="py-3 px-4">
                        {newsItem.author_id ? (
                          <div className="flex items-center gap-3">
                            {newsItem.author_image ? (
                              <img 
                                src={newsItem.author_image} 
                                alt={newsItem.author_name}
                                className="w-10 h-10 rounded-full object-cover border-2 border-[#0B6D76]/20"
                              />
                            ) : (
                              <div className="w-10 h-10 rounded-full bg-linear-to-b from-[#0B6D76]/10 to-[#094F56]/10 flex items-center justify-center">
                                <User size={16} className="text-[#0B6D76]" />
                              </div>
                            )}
                            <div>
                              <div className="font-medium text-gray-800 flex items-center gap-2">
                                {newsItem.author_name}
                              </div>
                              {newsItem.author_slug && (
                                <div className="text-xs text-gray-500 font-mono">@{newsItem.author_slug}</div>
                              )}
                            </div>
                          </div>
                        ) : (
                          <div className="flex flex-col gap-2">
                            <div className="text-gray-500 italic text-sm">No Author Assigned</div>
                            <button
                              onClick={() => handleAssignAuthor(newsItem.id, newsItem.author_id)}
                              className="text-xs bg-linear-to-b from-[#0B6D76]/10 to-[#094F56]/10 text-[#0B6D76] px-2 py-1 rounded hover:from-[#0B6D76]/20 hover:to-[#094F56]/20 transition-all"
                            >
                              Assign Author
                            </button>
                          </div>
                        )}
                      </td>
                      
                      {/* Featured Column */}
                      <td className="py-3 px-4 text-center">
                        <label className="relative inline-flex items-center cursor-pointer">
                          <input
                            type="checkbox"
                            checked={!!newsItem.is_featured}
                            onChange={() => toggleFeaturedStatus(newsItem.id, newsItem.is_featured)}
                            className="sr-only peer"
                          />
                          <div className="w-11 h-6 bg-gray-200 rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:left-0.5 after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-yellow-500"></div>
                          <span className="ml-2 text-sm font-medium text-gray-900">
                            {newsItem.is_featured ? '⭐ Featured' : 'Normal'}
                          </span>
                        </label>
                      </td>
                      
                      {/* Active Column */}
                      <td className="py-3 px-4 text-center">
                        <label className="relative inline-flex items-center cursor-pointer">
                          <input
                            type="checkbox"
                            checked={!!newsItem.is_active}
                            onChange={() => toggleActiveStatus(newsItem.id, newsItem.is_active)}
                            className="sr-only peer"
                          />
                          <div className="w-11 h-6 bg-gray-200 rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:left-0.5 after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-green-500"></div>
                          <span className={`ml-2 text-sm font-semibold ${newsItem.is_active ? 'text-green-600' : 'text-red-600'}`}>
                            {newsItem.is_active ? 'Active' : 'Inactive'}
                          </span>
                        </label>
                      </td>
                      
                      <td className="py-3 px-4 text-gray-600">
                        {newsItem.created_at ? formatDate(newsItem.created_at) : '-'}
                      </td>
                      
                      <td className="py-3 px-4">
                        <div className="flex gap-2 justify-center">
                          <button
                            onClick={() => handleEdit(newsItem.id)}
                            className="p-2 text-[#0B6D76] hover:bg-[#0B6D76]/10 rounded-lg transition-all flex items-center gap-1"
                            title="Edit News"
                          >
                            <Pencil className="w-4 h-4" />
                            <span className="text-sm">Edit</span>
                          </button>
                          <button
                            onClick={() => handleDelete(newsItem.id)}
                            className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-all flex items-center gap-1"
                            title="Delete News"
                          >
                            <Trash2 className="w-4 h-4" />
                            <span className="text-sm">Delete</span>
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination Component */}
        {totalPages > 1 && (
          <Pagination
            currentPage={currentPage}
            totalPages={totalPages}
            onPageChange={setCurrentPage}
            totalItems={totalItems}
            startIndex={startIndex}
            endIndex={endIndex}
          />
        )}
        
        {/* Results Summary */}
        <div className="mt-4 text-sm text-gray-600 text-center">
          Showing {startIndex + 1} to {Math.min(endIndex, totalItems)} of {totalItems} news items
          {hasActiveFilters && ' (filtered results)'}
        </div>
      </div>

      {selectedNewsId && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-lg shadow-lg max-h-[80vh] overflow-y-auto">
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-lg font-semibold">Comments for News #{selectedNewsId}</h2>
              <button onClick={closeModal} className="text-gray-500 hover:text-black text-2xl">&times;</button>
            </div>
            {commentLoading ? (
              <div className="flex justify-center">
                <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-[#0B6D76]"></div>
              </div>
            ) : comments.length === 0 ? (
              <p className="text-gray-500 text-center py-4">No comments found.</p>
            ) : (
              <ul className="space-y-4">
                {comments.map((comment) => (
                  <li key={comment.id} className="border-b pb-2">
                    <p className="text-sm text-gray-700">
                      <strong>{comment.first_name} {comment.last_name}</strong> ({comment.email})
                    </p>
                    <p className="text-gray-600 text-sm mt-1">{comment.comment}</p>
                  </li>
                ))}
              </ul>
            )}
          </div>
        </div>
      )}
    </div>
  );
}