'use client'

import { useEffect, useState } from 'react'
import Image from 'next/image'
import Link from 'next/link'
import { useParams } from 'next/navigation'
import { ArrowLeft, Calendar } 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 NewsArticleDetailPage() {
  const params = useParams<{ id: string }>()
  const articleId = Array.isArray(params?.id) ? params.id[0] : params?.id

  const [article, setArticle] = useState<NewsArticle | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState('')

  useEffect(() => {
    if (!articleId) {
      setError('Article not found.')
      setIsLoading(false)
      return
    }

    const fetchArticle = async () => {
      try {
        const result = await newsArticlesApi.getById(articleId)
        setArticle(result)
      } catch (err) {
        console.error('Error fetching news article:', err)
        setError('The requested article could not be loaded.')
      } finally {
        setIsLoading(false)
      }
    }

    fetchArticle()
  }, [articleId])

  return (
    <div className="min-h-screen py-12 px-4">
      <div className="max-w-[1100px] mx-auto">
        <div className="glass-page rounded-2xl p-8 md:p-12 shadow-2xl">
          <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>
            <Link href="/news" className="hover:text-primary transition-colors">News</Link>
          </div>

          <Link
            href="/news"
            className="inline-flex items-center gap-2 text-primary font-semibold hover:gap-3 transition-all mb-8"
          >
            <ArrowLeft className="w-4 h-4" />
            Back To News
          </Link>

          {isLoading ? (
            <div className="text-center py-12 text-white/70">
              Loading article...
            </div>
          ) : error || !article ? (
            <div className="text-center py-12">
              <p className="text-white/80 text-lg mb-3">{error || 'Article not found.'}</p>
              <Link href="/news" className="text-primary font-semibold hover:text-primary-light transition-colors">
                Return to news
              </Link>
            </div>
          ) : (
            <article>
              <div className="flex items-center gap-3 text-white/70 text-sm mb-4">
                <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>

              <h1 className="text-4xl md:text-5xl font-bold text-white mb-6">
                {article.title}
              </h1>

              <div className="relative h-64 md:h-[420px] rounded-2xl overflow-hidden mb-8">
                <Image
                  src={normalizeImageUrl(article.imageUrl) || '/news-carousel-default.jpg'}
                  alt={article.title}
                  fill
                  className="object-cover"
                />
              </div>

              <div className="prose prose-invert max-w-none">
                <p className="text-xl text-white/85 leading-relaxed mb-6">
                  {article.description}
                </p>
                {article.content ? (
                  <div
                    className="text-white/80 leading-8"
                    dangerouslySetInnerHTML={{ __html: article.content }}
                  />
                ) : (
                  <p className="text-white/80 leading-8 whitespace-pre-line">
                    {article.description}
                  </p>
                )}
              </div>
            </article>
          )}
        </div>
      </div>
    </div>
  )
}
