import type { Metadata } from 'next/types'

import configPromise from '@payload-config'
import { getPayload } from 'payload'
import Link from 'next/link'
import React from 'react'

import { StoryGrid } from '@/components/StoryGrid'


export default async function HomePage() {
  const payload = await getPayload({ config: configPromise })

  const [featuredStories, recentStories] = await Promise.all([
    (payload as any).find({
      collection: 'stories',
      sort: '-publishedAt',
      limit: 10,
      depth: 1,
      overrideAccess: false,
    }).catch(() => ({ docs: [], totalDocs: 0 })),
    (payload as any).find({
      collection: 'stories',
      sort: '-updatedAt',
      limit: 10,
      depth: 0,
      overrideAccess: false,
      select: { title: true, slug: true, publishedAt: true },
    }).catch(() => ({ docs: [] })),
  ])

  return (
    <div className="py-8">
      <section className="container mb-12">
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-2xl font-bold">Truyện Mới Cập Nhật</h2>
          <Link href="/truyen-moi" className="text-sm text-primary hover:underline">
            Xem tất cả →
          </Link>
        </div>
        <StoryGrid stories={featuredStories.docs} />
      </section>

      {recentStories.docs.length > 0 && (
        <section className="container">
          <h2 className="text-xl font-bold mb-4">Vừa Cập Nhật</h2>
          <div className="border border-border rounded-lg overflow-hidden">
            {recentStories.docs.map((story: any) => (
              <Link
                key={String(story.id)}
                href={`/truyen/${story.slug}`}
                className="flex items-center justify-between px-4 py-3 border-b border-border last:border-0 hover:bg-accent transition-colors"
              >
                <span className="font-medium text-sm line-clamp-1">{story.title}</span>
                {story.publishedAt && (
                  <span className="text-xs text-muted-foreground ml-4 flex-shrink-0">
                    {new Date(story.publishedAt).toLocaleDateString('vi-VN')}
                  </span>
                )}
              </Link>
            ))}
          </div>
        </section>
      )}

      {featuredStories.totalDocs === 0 && (
        <div className="container text-center py-24 text-muted-foreground">
          <p className="text-lg mb-2">Chưa có truyện nào.</p>
          <p className="text-sm">Thêm truyện trong admin panel để bắt đầu.</p>
        </div>
      )}
    </div>
  )
}

export function generateMetadata(): Metadata {
  return {
    title: 'Truyện Hay - Đọc Truyện Online',
    description: 'Kho truyện hay, đọc truyện online miễn phí',
  }
}
