'use client'

import { useState, useEffect } from 'react'
import Link from 'next/link'
import Image from 'next/image'
import { motion } from 'framer-motion'
import { Calendar, ArrowRight } from 'lucide-react'
import { newsArticlesApi, NewsArticle } from '@/lib/api'
import { normalizeImageUrl } from '@/lib/media'

const formatDate = (dateString: string | undefined) => {
  if (!dateString) return 'Date TBA'
  const date = new Date(dateString)
  return date.toLocaleDateString('en-ZA', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

export default function NewsPage() {
  const [articles, setArticles] = useState<NewsArticle[]>([])
  const [featuredArticle, setFeaturedArticle] = useState<NewsArticle | null>(null)
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    const fetchArticles = async () => {
      try {
        // Fetch all published articles
        const result = await newsArticlesApi.getAll({ limit: 100 })
        const allArticles = result.data

        // Sort by order (ascending - lowest order first), then by publishedAt (descending)
        const sortedArticles = [...allArticles].sort((a, b) => {
          const orderA = a.order ?? 0
          const orderB = b.order ?? 0
          
          if (orderA !== orderB) {
            return orderA - orderB // Lower order number first
          }
          
          // If orders are equal, sort by publishedAt (newest first)
          const dateA = new Date(a.publishedAt || a.createdAt).getTime()
          const dateB = new Date(b.publishedAt || b.createdAt).getTime()
          return dateB - dateA
        })

        // The article with the lowest order is the featured article
        if (sortedArticles.length > 0) {
          setFeaturedArticle(sortedArticles[0])
          setArticles(sortedArticles.slice(1)) // Rest of the articles
        } else {
          setArticles([])
        }
      } catch (error) {
        console.error('Error fetching news articles:', error)
        setArticles([])
      } finally {
        setIsLoading(false)
      }
    }

    fetchArticles()
  }, [])

  return (
    <div className="min-h-screen py-12 px-4">
      <div className="max-w-[1200px] mx-auto">
        <div className="glass-page rounded-2xl p-8 md:p-12 shadow-2xl">
          {/* Header Section */}
          <div className="text-center mb-12">
            <div className="flex items-center justify-center gap-2 mb-4">
              <span className="text-primary text-2xl">★</span>
              <h1 className="text-primary text-2xl font-bold uppercase">MADIBENG</h1>
            </div>
            <h2 className="text-4xl md:text-5xl font-bold text-white mb-4">News & Updates</h2>
            <div className="w-24 h-1 bg-primary mx-auto"></div>
          </div>

          {/* Breadcrumb */}
          <div className="mb-8 text-white/70 text-sm">
            <Link href="/home" className="hover:text-primary transition-colors">Home</Link>
            <span className="mx-2">/</span>
            <span>News</span>
          </div>

          {isLoading ? (
            <div className="text-center py-12 text-white/70">
              Loading news articles...
            </div>
          ) : (
            <>
              {/* Featured Article (Lowest Order) */}
              {featuredArticle && (
                <motion.article
                  initial={{ opacity: 0, y: 30 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.6 }}
                  className="mb-12"
                >
                  <Link
                    href={featuredArticle.link || `/news/${featuredArticle._id}`}
                    className="block glass rounded-2xl overflow-hidden hover:bg-white/10 transition-all duration-300 glass-hover group"
                  >
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-0">
                      {/* Featured Image */}
                      <div className="relative h-64 lg:h-96 overflow-hidden">
                        <Image
                          src={normalizeImageUrl(featuredArticle.imageUrl) || '/news-carousel-default.jpg'}
                          alt={featuredArticle.title}
                          fill
                          className="object-cover group-hover:scale-105 transition-transform duration-300"
                        />
                        <div className="absolute top-4 left-4">
                          <span className="px-3 py-1 bg-primary text-white text-sm font-bold rounded-full">
                            Featured
                          </span>
                        </div>
                      </div>

                      {/* Featured Content */}
                      <div className="p-6 lg:p-8 flex flex-col justify-center">
                        <div className="flex items-center gap-3 text-white/70 text-sm mb-4">
                          <Calendar className="w-4 h-4" />
                          <span>{formatDate(featuredArticle.publishedAt || featuredArticle.createdAt)}</span>
                          {featuredArticle.category && (
                            <span className="px-2 py-1 bg-white/20 text-white rounded-full text-xs">
                              {featuredArticle.category}
                            </span>
                          )}
                        </div>
                        <h3 className="text-3xl lg:text-4xl font-bold text-white mb-4 group-hover:text-primary-light transition-colors">
                          {featuredArticle.title}
                        </h3>
                        <p className="text-white/80 text-lg mb-6 leading-relaxed">
                          {featuredArticle.description}
                        </p>
                        <div className="flex items-center gap-2 text-primary font-semibold group-hover:gap-3 transition-all">
                          <span>Read More</span>
                          <ArrowRight className="w-5 h-5" />
                        </div>
                      </div>
                    </div>
                  </Link>
                </motion.article>
              )}

              {/* Other Articles Grid */}
              {articles.length > 0 ? (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  {articles.map((article, index) => (
                    <motion.article
                      key={article._id}
                      initial={{ opacity: 0, y: 30 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ duration: 0.4, delay: index * 0.1 }}
                      className="glass rounded-2xl overflow-hidden hover:bg-white/10 transition-all duration-300 glass-hover group"
                    >
                      <Link
                        href={article.link || `/news/${article._id}`}
                        className="block"
                      >
                        {/* Article Image */}
                        <div className="relative h-48 overflow-hidden">
                          <Image
                            src={normalizeImageUrl(article.imageUrl) || '/news-carousel-default.jpg'}
                            alt={article.title}
                            fill
                            className="object-cover group-hover:scale-105 transition-transform duration-300"
                          />
                        </div>

                        {/* Article Content */}
                        <div className="p-6">
                          <div className="flex items-center gap-2 text-white/70 text-sm mb-3">
                            <Calendar className="w-4 h-4" />
                            <span>{formatDate(article.publishedAt || article.createdAt)}</span>
                            {article.category && (
                              <span className="px-2 py-1 bg-white/20 text-white rounded-full text-xs">
                                {article.category}
                              </span>
                            )}
                          </div>
                          <h3 className="text-xl font-bold text-white mb-3 group-hover:text-primary-light transition-colors line-clamp-2">
                            {article.title}
                          </h3>
                          <p className="text-white/80 mb-4 line-clamp-3">
                            {article.description}
                          </p>
                          <div className="flex items-center gap-2 text-primary font-semibold text-sm group-hover:gap-3 transition-all">
                            <span>Read More</span>
                            <ArrowRight className="w-4 h-4" />
                          </div>
                        </div>
                      </Link>
                    </motion.article>
                  ))}
                </div>
              ) : featuredArticle ? null : (
                <div className="text-center py-12">
                  <p className="text-white/70 text-lg mb-2">No news articles available at this time.</p>
                  <p className="text-white/50 text-sm">Please check back later for updates.</p>
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  )
}
