import { sql } from '@vercel/postgres'
import Image from 'next/image'
import Link from 'next/link'

async function getArticlesWithTags() {
  try {
    const { rows } = await sql`
      SELECT * FROM articles_with_tags
      ORDER BY published_at DESC
      LIMIT 20
    `
    return rows
  } catch (error) {
    console.error('Error fetching articles:', error)
    return []
  }
}

async function getFeaturedArticle() {
  try {
    const { rows } = await sql`
      SELECT * FROM articles_with_tags
      ORDER BY view_count DESC
      LIMIT 1
    `
    return rows[0] || null
  } catch (error) {
    return null
  }
}

async function getTrendingTags() {
  try {
    const { rows } = await sql`
      SELECT t.name_burmese, t.slug, COUNT(at.article_id) as count
      FROM tags t
      JOIN article_tags at ON t.id = at.tag_id
      JOIN articles a ON at.article_id = a.id
      WHERE a.status = 'published'
      GROUP BY t.id
      ORDER BY count DESC
      LIMIT 15
    `
    return rows
  } catch (error) {
    return []
  }
}

export default async function ImprovedHome() {
  const [articles, featured, trendingTags] = await Promise.all([
    getArticlesWithTags(),
    getFeaturedArticle(),
    getTrendingTags()
  ])

  return (
    <div className="min-h-screen bg-gradient-to-b from-gray-50 to-white">
      {/* Hero Section with Featured Article */}
      {featured && (
        <section className="relative h-[600px] w-full overflow-hidden fade-in">
          <Image
            src={featured.featured_image || '/placeholder.jpg'}
            alt={featured.title_burmese}
            fill
            className="object-cover"
            priority
          />
          <div className="absolute inset-0 bg-gradient-to-t from-black via-black/60 to-transparent" />
          
          <div className="absolute inset-0 flex items-end">
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-16 w-full">
              <div className="max-w-3xl">
                {/* Category Badge */}
                <Link 
                  href={`/category/${featured.category_slug}`}
                  className="inline-block mb-4 px-4 py-2 bg-primary rounded-full text-white font-semibold text-sm hover:bg-primary-dark transition-colors"
                >
                  {featured.category_name_burmese}
                </Link>
                
                {/* Title */}
                <h1 className="text-5xl md:text-6xl font-bold text-white mb-4 font-burmese leading-tight">
                  <Link href={`/article/${featured.slug}`} className="hover:text-gray-200 transition-colors">
                    {featured.title_burmese}
                  </Link>
                </h1>
                
                {/* Excerpt */}
                <p className="text-xl text-gray-200 mb-6 font-burmese line-clamp-2">
                  {featured.excerpt_burmese}
                </p>
                
                {/* Tags */}
                {featured.tags_burmese && featured.tags_burmese.length > 0 && (
                  <div className="flex flex-wrap gap-2 mb-6">
                    {featured.tags_burmese.slice(0, 5).map((tag: string, idx: number) => (
                      <Link
                        key={idx}
                        href={`/tag/${featured.tag_slugs[idx]}`}
                        className="px-3 py-1 bg-white/20 backdrop-blur-sm text-white rounded-full text-sm hover:bg-white/30 transition-colors"
                      >
                        #{tag}
                      </Link>
                    ))}
                  </div>
                )}
                
                {/* Read More Button */}
                <Link
                  href={`/article/${featured.slug}`}
                  className="inline-flex items-center px-8 py-4 bg-white text-gray-900 rounded-full font-semibold hover:bg-gray-100 transition-all hover:shadow-xl font-burmese"
                >
                  ဖတ်ရန် →
                </Link>
              </div>
            </div>
          </div>
        </section>
      )}

      {/* Main Content */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        {/* Trending Tags */}
        {trendingTags.length > 0 && (
          <section className="mb-12 fade-in">
            <h2 className="text-2xl font-bold text-gray-900 mb-6 font-burmese flex items-center">
              🔥 လူကြိုက်များသော အကြောင်းအရာများ
            </h2>
            <div className="flex flex-wrap gap-3">
              {trendingTags.map((tag: any) => (
                <Link
                  key={tag.slug}
                  href={`/tag/${tag.slug}`}
                  className="tag tag-burmese"
                >
                  #{tag.name_burmese}
                  <span className="ml-2 text-xs opacity-60">({tag.count})</span>
                </Link>
              ))}
            </div>
          </section>
        )}

        {/* Article Grid */}
        <section className="fade-in">
          <h2 className="text-3xl font-bold text-gray-900 mb-8 font-burmese">
            နောက်ဆုံးရ သတင်းများ
          </h2>
          
          {articles.length === 0 ? (
            <div className="text-center py-20 bg-white rounded-2xl shadow-sm">
              <div className="text-6xl mb-4">📰</div>
              <p className="text-xl text-gray-500 font-burmese">
                သတင်းမရှိသေးပါ။ မကြာမီ ပြန်စစ်ကြည့်ပါ။
              </p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
              {articles.map((article: any) => (
                <article key={article.id} className="card card-hover fade-in">
                  {/* Cover Image */}
                  {article.featured_image && (
                    <Link href={`/article/${article.slug}`} className="block image-zoom">
                      <div className="relative h-56 w-full">
                        <Image
                          src={article.featured_image}
                          alt={article.title_burmese}
                          fill
                          className="object-cover"
                        />
                      </div>
                    </Link>
                  )}
                  
                  <div className="p-6">
                    {/* Category Badge */}
                    <Link
                      href={`/category/${article.category_slug}`}
                      className="inline-block mb-3 px-3 py-1 bg-primary/10 text-primary rounded-full text-xs font-semibold hover:bg-primary hover:text-white transition-all"
                    >
                      {article.category_name_burmese}
                    </Link>
                    
                    {/* Title */}
                    <h3 className="text-xl font-bold text-gray-900 mb-3 font-burmese line-clamp-2 hover:text-primary transition-colors">
                      <Link href={`/article/${article.slug}`}>
                        {article.title_burmese}
                      </Link>
                    </h3>
                    
                    {/* Excerpt */}
                    <p className="text-gray-600 mb-4 font-burmese line-clamp-3 text-sm leading-relaxed">
                      {article.excerpt_burmese}
                    </p>
                    
                    {/* Tags */}
                    {article.tags_burmese && article.tags_burmese.length > 0 && (
                      <div className="flex flex-wrap gap-2 mb-4">
                        {article.tags_burmese.slice(0, 3).map((tag: string, idx: number) => (
                          <Link
                            key={idx}
                            href={`/tag/${article.tag_slugs[idx]}`}
                            className="text-xs px-2 py-1 bg-gray-100 text-gray-700 rounded hover:bg-gray-200 transition-colors"
                          >
                            #{tag}
                          </Link>
                        ))}
                      </div>
                    )}
                    
                    {/* Meta */}
                    <div className="flex items-center justify-between text-sm text-gray-500 pt-4 border-t border-gray-100">
                      <span className="font-burmese">{article.reading_time} မိနစ်</span>
                      <span>{article.view_count} views</span>
                    </div>
                  </div>
                </article>
              ))}
            </div>
          )}
        </section>

        {/* Load More Button */}
        {articles.length >= 20 && (
          <div className="text-center mt-12">
            <button className="px-8 py-4 bg-primary text-white rounded-full font-semibold hover:bg-primary-dark transition-all hover:shadow-xl font-burmese">
              နောက်ထပ် ဖတ်ရန် →
            </button>
          </div>
        )}
      </div>
    </div>
  )
}
