'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { Search, Plus, Edit, Trash2, Eye, EyeOff, Filter, CheckSquare, Square, X, Send, CheckCircle, Clock, LayoutGrid, List } from 'lucide-react'
import { isAuthenticated, hasRole, getAdminUser } from '@/lib/auth'
import { apiGet, apiDelete, apiPut, apiPost } from '@/lib/apiClient'
import { normalizeImageUrl } from '@/lib/media'
import LoadingSpinner from '@/components/LoadingSpinner'

interface NewsArticle {
  _id: string
  title: string
  description: string
  imageUrl: string
  category: string
  status?: 'draft' | 'pending_review' | 'published'
  isPublished: boolean
  isFeatured: boolean
  publishedAt?: string
  createdAt: string
  createdBy?: {
    _id: string
    firstName: string
    lastName: string
    email: string
  }
}

export default function NewsArticlesPage() {
  const router = useRouter()
  const [articles, setArticles] = useState<NewsArticle[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [filterCategory, setFilterCategory] = useState('all')
  const [filterStatus, setFilterStatus] = useState('all')
  const [selectedArticles, setSelectedArticles] = useState<Set<string>>(new Set())
  const [bulkMode, setBulkMode] = useState(false)
  const [currentUser, setCurrentUser] = useState<any>(null)
  const [viewMode, setViewMode] = useState<'list' | 'grid'>('list')
  const [isManager, setIsManager] = useState(false)
  const [canCreate, setCanCreate] = useState(false)

  useEffect(() => {
    // Check authentication
    if (!isAuthenticated()) {
      router.push('/admin')
      return
    }
    const user = getAdminUser()
    setCurrentUser(user)
    setIsManager(hasRole(['ADMINISTRATOR', 'COMMUNICATIONS_MANAGER']))
    setCanCreate(hasRole(['ADMINISTRATOR', 'COMMUNICATIONS_MANAGER', 'SENIOR_COMMUNICATIONS_OFFICER', 'COMMUNICATIONS_OFFICER']))
    fetchArticles()
  }, [router])

  const fetchArticles = async () => {
    try {
      const result = await apiGet<NewsArticle[]>('/news-articles/all')
      if (result.success && result.data) {
        setArticles(result.data)
      }
    } catch (error: any) {
      console.error('Error fetching articles:', error)
      if (error.message?.includes('Authentication required')) {
        router.push('/admin')
      }
    } finally {
      setLoading(false)
    }
  }

  const handleDelete = async (id: string) => {
    if (!confirm('Are you sure you want to delete this article?')) return

    try {
      const result = await apiDelete(`/news-articles/${id}`)
      if (result.success) {
        fetchArticles()
      }
    } catch (error: any) {
      console.error('Error deleting article:', error)
      alert(error.message || 'Failed to delete article')
    }
  }

  const togglePublish = async (id: string, currentStatus: boolean) => {
    try {
      const result = await apiPut(`/news-articles/${id}`, {
        isPublished: !currentStatus
      })
      if (result.success) {
        fetchArticles()
      }
    } catch (error: any) {
      console.error('Error toggling publish status:', error)
      alert(error.message || 'Failed to update publish status')
    }
  }

  // Bulk operations
  const toggleSelection = (id: string) => {
    const newSelection = new Set(selectedArticles)
    if (newSelection.has(id)) {
      newSelection.delete(id)
    } else {
      newSelection.add(id)
    }
    setSelectedArticles(newSelection)
  }

  const selectAll = () => {
    if (selectedArticles.size === filteredArticles.length) {
      setSelectedArticles(new Set())
    } else {
      setSelectedArticles(new Set(filteredArticles.map(a => a._id)))
    }
  }

  const bulkPublish = async () => {
    if (selectedArticles.size === 0) return
    if (!confirm(`Publish ${selectedArticles.size} article(s)?`)) return

    try {
      const promises = Array.from(selectedArticles).map(id =>
        apiPut(`/news-articles/${id}`, { isPublished: true })
      )
      await Promise.all(promises)
      setSelectedArticles(new Set())
      fetchArticles()
    } catch (error: any) {
      console.error('Error bulk publishing:', error)
      alert(error.message || 'Failed to publish articles')
    }
  }

  const bulkUnpublish = async () => {
    if (selectedArticles.size === 0) return
    if (!confirm(`Unpublish ${selectedArticles.size} article(s)?`)) return

    try {
      const promises = Array.from(selectedArticles).map(id =>
        apiPut(`/news-articles/${id}`, { isPublished: false })
      )
      await Promise.all(promises)
      setSelectedArticles(new Set())
      fetchArticles()
    } catch (error: any) {
      console.error('Error bulk unpublishing:', error)
      alert(error.message || 'Failed to unpublish articles')
    }
  }

  const bulkDelete = async () => {
    if (selectedArticles.size === 0) return
    if (!confirm(`Delete ${selectedArticles.size} article(s)? This action cannot be undone!`)) return

    try {
      const promises = Array.from(selectedArticles).map(id =>
        apiDelete(`/news-articles/${id}`)
      )
      await Promise.all(promises)
      setSelectedArticles(new Set())
      fetchArticles()
    } catch (error: any) {
      console.error('Error bulk deleting:', error)
      alert(error.message || 'Failed to delete articles')
    }
  }

  const filteredArticles = articles.filter(article => {
    const matchesSearch = article.title.toLowerCase().includes(searchTerm.toLowerCase())
    const matchesCategory = filterCategory === 'all' || article.category === filterCategory
    
    let matchesStatus = true
    if (filterStatus === 'published') {
      matchesStatus = article.isPublished && article.status === 'published'
    } else if (filterStatus === 'pending_review') {
      matchesStatus = article.status === 'pending_review'
    } else if (filterStatus === 'draft') {
      matchesStatus = article.status === 'draft' || (!article.status && !article.isPublished)
    } else if (filterStatus === 'all') {
      matchesStatus = true
    }
    
    return matchesSearch && matchesCategory && matchesStatus
  })
  
  const handleSubmitForReview = async (id: string) => {
    try {
      const result = await apiPost(`/news-articles/${id}/submit-for-review`)
      if (result.success) {
        fetchArticles()
      }
    } catch (error: any) {
      console.error('Error submitting for review:', error)
      alert(error.message || 'Failed to submit article for review')
    }
  }
  
  const handleReview = async (id: string, action: 'approve' | 'reject') => {
    try {
      const result = await apiPost(`/news-articles/${id}/review`, { action })
      if (result.success) {
        fetchArticles()
      }
    } catch (error: any) {
      console.error('Error reviewing article:', error)
      alert(error.message || `Failed to ${action} article`)
    }
  }
  
  const getStatusBadge = (article: NewsArticle) => {
    const status = article.status || (article.isPublished ? 'published' : 'draft')
    switch (status) {
      case 'published':
        return <span className="px-2 py-1 text-xs font-medium rounded bg-green-500/20 text-green-400">Published</span>
      case 'pending_review':
        return <span className="px-2 py-1 text-xs font-medium rounded bg-yellow-500/20 text-yellow-400">Pending Review</span>
      case 'draft':
        return <span className="px-2 py-1 text-xs font-medium rounded bg-gray-500/20 text-gray-400">Draft</span>
      default:
        return <span className="px-2 py-1 text-xs font-medium rounded bg-gray-500/20 text-gray-400">Draft</span>
    }
  }
  
  const isArticleOwner = (article: NewsArticle) => {
    return currentUser && article.createdBy && article.createdBy._id === currentUser.id
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <LoadingSpinner />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-white mb-2">News Articles</h1>
          <p className="text-white/70">Manage news articles and publications</p>
        </div>
        <div className="flex gap-3">
          {/* View Toggle */}
          <div className="flex items-center bg-white/10 rounded-lg p-1">
            <button
              onClick={() => setViewMode('list')}
              className={`p-2 rounded transition-all ${
                viewMode === 'list' ? 'bg-primary text-white' : 'text-white/50 hover:text-white'
              }`}
              title="List View"
            >
              <List className="w-5 h-5" />
            </button>
            <button
              onClick={() => setViewMode('grid')}
              className={`p-2 rounded transition-all ${
                viewMode === 'grid' ? 'bg-primary text-white' : 'text-white/50 hover:text-white'
              }`}
              title="Grid View"
            >
              <LayoutGrid className="w-5 h-5" />
            </button>
          </div>
          <button
            onClick={() => {
              setBulkMode(!bulkMode)
              setSelectedArticles(new Set())
            }}
            className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-all ${
              bulkMode ? 'bg-orange-500 hover:bg-orange-600' : 'bg-white/10 hover:bg-white/20'
            } text-white`}
          >
            {bulkMode ? <X className="w-5 h-5" /> : <CheckSquare className="w-5 h-5" />}
            {bulkMode ? 'Exit Bulk Mode' : 'Bulk Operations'}
          </button>
        {canCreate && (
          <button
            onClick={() => router.push('/admin/news-articles/new')}
            className="flex items-center gap-2 px-4 py-2 bg-primary hover:bg-primary-dark text-white rounded-lg transition-all"
          >
            <Plus className="w-5 h-5" />
            New Article
          </button>
        )}
        </div>
      </div>

      {/* Filters */}
      <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
        <div className={`grid grid-cols-1 gap-4 ${bulkMode ? 'md:grid-cols-4' : 'md:grid-cols-3'}`}>
          {bulkMode && (
            <div>
              <button
                onClick={selectAll}
                className="w-full px-4 py-2 bg-white/10 hover:bg-white/20 border border-white/20 rounded-lg text-white transition-all"
              >
                {selectedArticles.size === filteredArticles.length ? 'Deselect All' : 'Select All'}
              </button>
            </div>
          )}
          
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-white/50" />
            <input
              type="text"
              placeholder="Search articles..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:ring-2 focus:ring-primary"
            />
          </div>

          <div className="relative">
            <Filter className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-white/50" />
            <select
              value={filterCategory}
              onChange={(e) => setFilterCategory(e.target.value)}
              className="w-full pl-10 pr-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary appearance-none"
            >
              <option value="all">All Categories</option>
              <option value="general">General</option>
              <option value="announcement">Announcement</option>
              <option value="event">Event</option>
              <option value="update">Update</option>
            </select>
          </div>

          <div>
            <select
              value={filterStatus}
              onChange={(e) => setFilterStatus(e.target.value)}
              className="w-full px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary appearance-none"
            >
              <option value="all">All Status</option>
              <option value="published">Published</option>
              <option value="pending_review">Pending Review</option>
              <option value="draft">Draft</option>
            </select>
          </div>
        </div>

        {/* Bulk Actions Bar */}
        {bulkMode && selectedArticles.size > 0 && (
          <div className="mt-4 pt-4 border-t border-white/20 flex items-center gap-3 flex-wrap">
            <span className="text-white/70 text-sm">
              {selectedArticles.size} article(s) selected
            </span>
            <div className="flex gap-2 flex-wrap">
              <button
                onClick={bulkPublish}
                className="flex items-center gap-2 px-4 py-2 bg-green-500/20 hover:bg-green-500/30 text-green-400 rounded-lg transition-all text-sm"
              >
                <Eye className="w-4 h-4" />
                Publish Selected
              </button>
              <button
                onClick={bulkUnpublish}
                className="flex items-center gap-2 px-4 py-2 bg-yellow-500/20 hover:bg-yellow-500/30 text-yellow-400 rounded-lg transition-all text-sm"
              >
                <EyeOff className="w-4 h-4" />
                Unpublish Selected
              </button>
              <button
                onClick={bulkDelete}
                className="flex items-center gap-2 px-4 py-2 bg-red-500/20 hover:bg-red-500/30 text-red-400 rounded-lg transition-all text-sm"
              >
                <Trash2 className="w-4 h-4" />
                Delete Selected
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Articles Display */}
      {viewMode === 'grid' ? (
        <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
          {filteredArticles.map((article) => (
          <div
            key={article._id}
            className={`bg-white/10 backdrop-blur-xl rounded-xl border overflow-hidden hover:border-white/40 transition-all group ${
              selectedArticles.has(article._id) ? 'border-primary ring-2 ring-primary' : 'border-white/20'
            }`}
          >
            {/* Article Image */}
            <div className="relative h-48 bg-white/5">
              {article.imageUrl ? (
                <img
                  src={normalizeImageUrl(article.imageUrl)}
                  alt={article.title}
                  className="w-full h-full object-cover"
                />
              ) : (
                <div className="w-full h-full flex items-center justify-center text-white/30">
                  No Image
                </div>
              )}
              
              {bulkMode && (
                <button
                  onClick={() => toggleSelection(article._id)}
                  className="absolute top-3 left-3 p-2 bg-black/50 backdrop-blur-sm rounded-lg hover:bg-black/70 transition-all"
                >
                  {selectedArticles.has(article._id) ? (
                    <CheckSquare className="w-6 h-6 text-primary" />
                  ) : (
                    <Square className="w-6 h-6 text-white" />
                  )}
                </button>
              )}

              <div className="absolute top-3 right-3 flex gap-2 flex-wrap">
                {article.isFeatured && (
                  <span className="px-2 py-1 bg-yellow-500 text-white text-xs font-medium rounded">
                    Featured
                  </span>
                )}
                {getStatusBadge(article)}
              </div>
            </div>

            {/* Article Content */}
            <div className="p-4">
              <h3 className="text-white font-semibold text-lg mb-2 line-clamp-2">
                {article.title}
              </h3>
              <p className="text-white/70 text-sm mb-3 line-clamp-2">
                {article.description}
              </p>
              <div className="flex items-center justify-between text-xs text-white/50 mb-4">
                <span>{article.category}</span>
                <span>{new Date(article.createdAt).toLocaleDateString()}</span>
              </div>

              {/* Actions */}
              {!bulkMode && (
                <div className="space-y-2">
                  <div className="flex items-center gap-2">
                    <button
                      onClick={() => router.push(`/admin/news-articles/${article._id}`)}
                      className="flex-1 flex items-center justify-center gap-2 px-3 py-2 bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 rounded-lg transition-all"
                    >
                      <Edit className="w-4 h-4" />
                      Edit
                    </button>
                    <button
                      onClick={() => handleDelete(article._id)}
                      className="p-2 bg-red-500/20 text-red-400 hover:bg-red-500/30 rounded-lg transition-all"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                  
                  {/* Workflow Actions */}
                  {(() => {
                    const status = article.status || (article.isPublished ? 'published' : 'draft')
                    const isOwner = isArticleOwner(article)
                    
                    // Manager actions
                    if (isManager) {
                      if (status === 'pending_review') {
                        return (
                          <div className="flex items-center gap-2">
                            <button
                              onClick={() => handleReview(article._id, 'approve')}
                              className="flex-1 flex items-center justify-center gap-2 px-3 py-2 bg-green-500/20 text-green-400 hover:bg-green-500/30 rounded-lg transition-all"
                            >
                              <CheckCircle className="w-4 h-4" />
                              Approve & Publish
                            </button>
                            <button
                              onClick={() => handleReview(article._id, 'reject')}
                              className="flex-1 flex items-center justify-center gap-2 px-3 py-2 bg-red-500/20 text-red-400 hover:bg-red-500/30 rounded-lg transition-all"
                            >
                              <X className="w-4 h-4" />
                              Reject
                            </button>
                          </div>
                        )
                      } else if (status === 'published') {
                        return (
                          <button
                            onClick={() => togglePublish(article._id, article.isPublished)}
                            className="w-full flex items-center justify-center gap-2 px-3 py-2 bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30 rounded-lg transition-all"
                          >
                            <EyeOff className="w-4 h-4" />
                            Unpublish
                          </button>
                        )
                      }
                    }
                    
                    // Content creator actions
                    if (isOwner && status === 'draft') {
                      return (
                        <button
                          onClick={() => handleSubmitForReview(article._id)}
                          className="w-full flex items-center justify-center gap-2 px-3 py-2 bg-purple-500/20 text-purple-400 hover:bg-purple-500/30 rounded-lg transition-all"
                        >
                          <Send className="w-4 h-4" />
                          Submit for Review
                        </button>
                      )
                    }
                    
                    if (isOwner && status === 'pending_review') {
                      return (
                        <div className="flex items-center gap-2 text-yellow-400 text-sm">
                          <Clock className="w-4 h-4" />
                          <span>Awaiting Manager Review</span>
                        </div>
                      )
                    }
                    
                    return null
                  })()}
                </div>
              )}
            </div>
          </div>
        ))}
        </div>
      ) : (
        <div className="bg-white/10 backdrop-blur-xl rounded-xl border border-white/20 overflow-hidden">
          <div className="divide-y divide-white/10">
            {filteredArticles.map((article) => (
              <div
                key={article._id}
                className={`p-4 hover:bg-white/5 transition-colors ${
                  selectedArticles.has(article._id) ? 'bg-primary/10 border-l-4 border-l-primary' : ''
                }`}
              >
                <div className="flex items-start gap-4">
                  {/* Bulk Select Checkbox */}
                  {bulkMode && (
                    <button
                      onClick={() => toggleSelection(article._id)}
                      className="flex-shrink-0 p-2 hover:bg-white/10 rounded-lg transition-all"
                    >
                      {selectedArticles.has(article._id) ? (
                        <CheckSquare className="w-5 h-5 text-primary" />
                      ) : (
                        <Square className="w-5 h-5 text-white/50" />
                      )}
                    </button>
                  )}

                  {/* Image Thumbnail */}
                  {article.imageUrl && (
                    <div className="flex-shrink-0 w-24 h-24 rounded-lg overflow-hidden bg-white/5">
                      <img
                        src={normalizeImageUrl(article.imageUrl)}
                        alt={article.title}
                        className="w-full h-full object-cover"
                      />
                    </div>
                  )}

                  {/* Content */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-start justify-between gap-3 mb-2">
                      <h3 className="text-white font-semibold text-lg line-clamp-1 flex-1">
                        {article.title}
                      </h3>
                      <div className="flex items-center gap-2 flex-shrink-0">
                        {article.isFeatured && (
                          <span className="px-2 py-1 bg-yellow-500 text-white text-xs font-medium rounded">
                            Featured
                          </span>
                        )}
                        {getStatusBadge(article)}
                      </div>
                    </div>
                    <p className="text-white/70 text-sm mb-3 line-clamp-2">
                      {article.description}
                    </p>
                    <div className="flex items-center gap-4 text-xs text-white/50 mb-3">
                      <span className="capitalize">{article.category}</span>
                      <span>{new Date(article.createdAt).toLocaleDateString()}</span>
                      {article.createdBy && (
                        <span>By {article.createdBy.firstName} {article.createdBy.lastName}</span>
                      )}
                    </div>

                    {/* Actions */}
                    {!bulkMode && (
                      <div className="flex items-center gap-2">
                        <button
                          onClick={() => router.push(`/admin/news-articles/${article._id}`)}
                          className="flex items-center gap-2 px-3 py-1.5 text-blue-400 hover:bg-blue-500/20 rounded-lg transition-all text-sm"
                        >
                          <Edit className="w-4 h-4" />
                          Edit
                        </button>

                        {(() => {
                          const status = article.status || (article.isPublished ? 'published' : 'draft')
                          const isOwner = isArticleOwner(article)
                          
                          // Manager actions
                          if (isManager) {
                            if (status === 'pending_review') {
                              return (
                                <>
                                  <button
                                    onClick={() => handleReview(article._id, 'approve')}
                                    className="flex items-center gap-2 px-3 py-1.5 text-green-400 hover:bg-green-500/20 rounded-lg transition-all text-sm"
                                  >
                                    <CheckCircle className="w-4 h-4" />
                                    Approve
                                  </button>
                                  <button
                                    onClick={() => handleReview(article._id, 'reject')}
                                    className="flex items-center gap-2 px-3 py-1.5 text-red-400 hover:bg-red-500/20 rounded-lg transition-all text-sm"
                                  >
                                    <X className="w-4 h-4" />
                                    Reject
                                  </button>
                                </>
                              )
                            } else if (status === 'published') {
                              return (
                                <button
                                  onClick={() => togglePublish(article._id, article.isPublished)}
                                  className="flex items-center gap-2 px-3 py-1.5 text-yellow-400 hover:bg-yellow-500/20 rounded-lg transition-all text-sm"
                                >
                                  <EyeOff className="w-4 h-4" />
                                  Unpublish
                                </button>
                              )
                            }
                          }
                          
                          // Content creator actions
                          if (isOwner && status === 'draft') {
                            return (
                              <button
                                onClick={() => handleSubmitForReview(article._id)}
                                className="flex items-center gap-2 px-3 py-1.5 text-purple-400 hover:bg-purple-500/20 rounded-lg transition-all text-sm"
                              >
                                <Send className="w-4 h-4" />
                                Submit for Review
                              </button>
                            )
                          }
                          
                          if (isOwner && status === 'pending_review') {
                            return (
                              <span className="flex items-center gap-2 text-yellow-400 text-sm px-3 py-1.5">
                                <Clock className="w-4 h-4" />
                                Pending Review
                              </span>
                            )
                          }
                          
                          return null
                        })()}

                        <button
                          onClick={() => handleDelete(article._id)}
                          className="flex items-center gap-2 px-3 py-1.5 text-red-400 hover:bg-red-500/20 rounded-lg transition-all text-sm"
                        >
                          <Trash2 className="w-4 h-4" />
                          Delete
                        </button>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {filteredArticles.length === 0 && (
        <div className="bg-white/10 backdrop-blur-xl rounded-xl p-12 text-center border border-white/20">
          <p className="text-white/50">No articles found</p>
        </div>
      )}
    </div>
  )
}
