'use client'

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

// Format date consistently to avoid hydration mismatch
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return 'Date TBA'
  const date = new Date(dateString)
  const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  return `${date.getDate()} ${months[date.getMonth()]} ${date.getFullYear()}`
}

export default function News() {
  const [newsItems, setNewsItems] = useState<NewsArticle[]>([])
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    const fetchNews = async () => {
      try {
        const result = await newsArticlesApi.getAll({ limit: 6 })
        setNewsItems(result.data)
      } catch (error) {
        console.error('Error fetching news articles:', error)
        setNewsItems([])
      } finally {
        setIsLoading(false)
      }
    }

    fetchNews()
  }, [])

  return (
    <section id="news" className="py-20">
      <div className="max-w-[900px] mx-auto px-4">
        <motion.div
          initial={{ opacity: 0, y: 30 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ duration: 0.8 }}
          className="text-center mb-16"
        >
          <h2 className="text-4xl md:text-5xl font-bold mb-4 text-white">
            Latest News & Updates
          </h2>
          <p className="text-xl text-white/80">
            Stay informed about municipal news and announcements
          </p>
        </motion.div>

        {isLoading ? (
          <div className="text-center text-white/70 py-12">
            Loading news...
          </div>
        ) : newsItems.length === 0 ? (
          <div className="text-center text-white/70 py-12">
            No news articles available at this time.
          </div>
        ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {newsItems.map((item, index) => (
            <motion.article
                key={item._id}
              initial={{ opacity: 0, y: 30 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: true }}
              transition={{ duration: 0.5, delay: index * 0.1 }}
              whileHover={{ y: -10 }}
              className="glass rounded-2xl p-6 shadow-lg glass-hover overflow-hidden group"
            >
              <div className="flex items-center gap-2 text-sm text-white/70 mb-4">
                <Calendar className="w-4 h-4" />
                  <span>{formatDate(item.publishedAt || item.createdAt)}</span>
                <span className="px-2 py-1 bg-white/20 text-white rounded-full text-xs">
                  {item.category}
                </span>
              </div>
              <h3 className="text-2xl font-bold text-white mb-3 group-hover:text-primary-light transition-colors">
                {item.title}
              </h3>
              <p className="text-white/80 mb-4">
                  {item.description}
              </p>
              <Link
                  href={item.link || `/news/${item._id}`}
                className="inline-flex items-center gap-2 text-primary-light font-semibold hover:gap-4 transition-all"
              >
                Read More <ArrowRight className="w-4 h-4" />
              </Link>
            </motion.article>
          ))}
        </div>
        )}
      </div>
    </section>
  )
}
