import { headers } from 'next/headers';
import Link from 'next/link';
import type { Metadata } from 'next';
import { fetchPosts, getMediaUrl } from '@/lib/api';
import Image from 'next/image';

export const metadata: Metadata = {
  title: 'Blog / Posts',
  description: 'Read our latest blog posts and announcements.'
};

interface SearchParams {
  page?: string;
}

export default async function PostListPage(props: { searchParams: Promise<SearchParams> }) {
  const searchParams = await props.searchParams;
  const page = parseInt(searchParams?.page || '1', 10);
  
  const headersList = await headers();
  const host = headersList.get('host') || '';
  const domainTheme = host.includes('rollerblindbekasi.in') ? 'rollerblindbekasi.in' : 
                      host.includes('rollerblindjakarta.in') ? 'rollerblindjakarta.in' : 
                      host;

  const postsData = await fetchPosts(domainTheme, page);

  if (!postsData) {
    return <div className="p-8 text-center">Gagal memuat artikel.</div>;
  }

  const { data: posts, current_page, last_page } = postsData;

  return (
    <div className="container mx-auto px-4 py-16 md:py-24 max-w-6xl">
      <div className="mb-12 text-center">
        <h1 className="text-4xl font-extrabold tracking-tight lg:text-5xl mb-4">Semua Artikel</h1>
        <p className="text-xl text-muted-foreground">Temukan seluruh koleksi artikel dan pembaruan kami.</p>
      </div>

      {posts.length === 0 ? (
        <div className="text-center py-10">
          <p className="text-muted-foreground">Tidak ada artikel ditemukan.</p>
        </div>
      ) : (
        <div className="grid grid-cols-2 md:grid-cols-2 lg:grid-cols-3 gap-8 mb-12">
          {posts.map((post: any) => (
            <article key={post.id} className="flex flex-col space-y-4 group">
              
              <Link href={`/post/${post.slug}`} className="block overflow-hidden rounded-xl bg-muted aspect-[16/9]">
                {/* <div className="w-full h-full bg-secondary/50 transition-colors group-hover:bg-primary/20 flex flex-col items-center justify-center p-6 text-center">
                    <h3 className="text-2xl font-serif text-primary/80 pointer-events-none select-none px-4 text-balance line-clamp-3">
                         {post.title}
                    </h3>
                </div> */}
                {
                  post.media ? 
                    <div className="aspect-video w-full overflow-hidden">
                    <Image
                      src={getMediaUrl(post.media)}
                      alt={post.title}
                      width={600}
                      height={400}
                      className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
                    />
                  </div>
                  :
                  <div className="w-full h-full  transition-colors group-hover:bg-primary/20 flex flex-col items-center justify-center p-6 text-center">
                      <h3 className="text-2xl font-serif text-primary/80 pointer-events-none select-none px-4 text-balance line-clamp-3">
                            {post.title}
                      </h3>
                  </div>
                }
              </Link>
              <div className="space-y-2 flex-grow">
                <Link href={`/post/${post.slug}`} className="hover:underline">
                  <h3 className="text-xl font-bold leading-tight line-clamp-2">{post.title}</h3>
                </Link>
                <p className="text-muted-foreground line-clamp-3 text-sm">
                  {post.description?.replace(/<[^>]*>?/gm, '').substring(0, 100)}...
                </p>
              </div>
            </article>
          ))}
        </div>
      )}

      {/* Pagination Controls */}
      {last_page > 1 && (
        <div className="flex justify-center items-center space-x-2 mt-8">
          {current_page > 1 && (
            <Link 
              href={`/post-list?page=${current_page - 1}`}
              className="px-4 py-2 border rounded-md hover:bg-muted transition-colors"
            >
              Sebelumnya
            </Link>
          )}
          <span className="text-sm text-muted-foreground">
            Halaman {current_page} dari {last_page}
          </span>
          {current_page < last_page && (
            <Link 
              href={`/post-list?page=${current_page + 1}`}
              className="px-4 py-2 border rounded-md hover:bg-muted transition-colors"
            >
              Selanjutnya
            </Link>
          )}
        </div>
      )}
    </div>
  );
}
