import { sql } from '@/lib/db'
export const dynamic = "force-dynamic"
import Link from 'next/link'
import Image from 'next/image'

async function searchArticles(query: string) {
  if (!query || query.trim().length < 2) return []
  try {
    const pattern = `%${query.trim()}%`
    const { rows } = await sql`
      SELECT
        a.id, a.title_burmese, a.slug, a.excerpt_burmese,
        a.featured_image, a.reading_time, a.view_count, a.published_at,
        c.name_burmese as category_name_burmese, c.slug as category_slug
      FROM articles a
      JOIN categories c ON a.category_id = c.id
      WHERE a.status = 'published'
        AND (
          a.title_burmese ILIKE ${pattern}
          OR a.excerpt_burmese ILIKE ${pattern}
          OR a.title ILIKE ${pattern}
        )
      ORDER BY a.published_at DESC
      LIMIT 20
    `
    return rows
  } catch {
    return []
  }
}

export default async function SearchPage({
  searchParams,
}: {
  searchParams: { q?: string }
}) {
  const query = searchParams.q ?? ''
  const results = await searchArticles(query)

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Search Header */}
      <div className="bg-white border-b border-gray-200">
        <div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
          <h1 className="text-2xl font-bold text-gray-900 mb-6 font-burmese">ရှာဖွေရန်</h1>
          <form action="/search" method="GET">
            <div className="relative">
              <svg
                className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400"
                fill="none" stroke="currentColor" viewBox="0 0 24 24"
              >
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
              </svg>
              <input
                type="search"
                name="q"
                defaultValue={query}
                placeholder="ဆောင်းပါးများ ရှာဖွေရန်..."
                className="w-full pl-12 pr-4 py-4 border-2 border-gray-200 rounded-2xl font-burmese text-lg focus:outline-none focus:border-primary transition-colors bg-gray-50"
                autoFocus
              />
            </div>
          </form>
        </div>
      </div>

      {/* Results */}
      <div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
        {query && (
          <p className="text-sm text-gray-500 mb-6 font-burmese">
            &ldquo;{query}&rdquo; အတွက် ရလဒ် {results.length} ခု
          </p>
        )}

        {!query && (
          <div className="text-center py-20 text-gray-400">
            <div className="text-6xl mb-4">🔍</div>
            <p className="font-burmese text-lg">ရှာဖွေလိုသည့် စကားလုံး ထည့်ပါ</p>
          </div>
        )}

        {query && results.length === 0 && (
          <div className="text-center py-20">
            <div className="text-6xl mb-4">😕</div>
            <p className="text-gray-500 font-burmese text-lg mb-4">ရလဒ်မတွေ့ပါ</p>
            <Link href="/" className="text-primary font-burmese hover:underline">
              ပင်မစာမျက်နှာသို့ ပြန်သွားရန်
            </Link>
          </div>
        )}

        <div className="space-y-6">
          {results.map((article: any) => (
            <Link
              key={article.id}
              href={`/article/${article.slug}`}
              className="flex gap-4 bg-white rounded-xl p-4 shadow-sm hover:shadow-md transition-all border border-gray-100 group"
            >
              {article.featured_image && (
                <div className="relative w-24 h-24 flex-shrink-0 rounded-lg overflow-hidden">
                  <Image
                    src={article.featured_image}
                    alt={article.title_burmese}
                    fill
                    className="object-cover"
                  />
                </div>
              )}
              <div className="flex-1 min-w-0">
                <span className="inline-block px-2 py-0.5 bg-primary/10 text-primary rounded text-xs font-burmese mb-2">
                  {article.category_name_burmese}
                </span>
                <h2 className="font-bold text-gray-900 font-burmese line-clamp-2 group-hover:text-primary transition-colors leading-snug mb-1">
                  {article.title_burmese}
                </h2>
                <p className="text-sm text-gray-500 font-burmese line-clamp-2 leading-relaxed">
                  {article.excerpt_burmese}
                </p>
              </div>
            </Link>
          ))}
        </div>
      </div>
    </div>
  )
}

export async function generateMetadata({ searchParams }: { searchParams: { q?: string } }) {
  const q = searchParams.q
  return {
    title: q ? `"${q}" - ရှာဖွေမှု - Burmddit` : 'ရှာဖွေရန် - Burmddit',
  }
}
