import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import Image from 'next/image';
import ArticleCard from '@/components/article/ArticleCard';
import Pagination from '@/components/ui/Pagination';
import { getImageUrl } from '@/utils';

interface Props { params: Promise<{ id: string }>; searchParams: Promise<{ page?: string }>; }

async function getAuthor(id: string, page: number) {
  try {
    const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/articles/author/${id}?page=${page}&limit=12`, { next: { revalidate: 120 } });
    if (!res.ok) return null;
    const json = await res.json();
    return { author: json.data?.author, articles: json.data?.articles || [], total: json.meta?.total || 0 };
  } catch { return null; }
}

const ROLE_LABEL: Record<string, string> = {
  super_admin: 'Editor-in-Chief', admin: 'Editor', editor: 'Editor', author: 'Staff Writer', moderator: 'Moderator', reader: 'Contributor',
};

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { id } = await params;
  const data = await getAuthor(id, 1);
  return { title: data?.author?.name || 'Author' };
}

export default async function AuthorPage({ params, searchParams }: Props) {
  const { id } = await params;
  const { page: pageStr } = await searchParams;
  const page = parseInt(pageStr || '1');

  const data = await getAuthor(id, page);
  if (!data || !data.author) notFound();

  const { author, articles, total } = data;
  const totalPages = Math.ceil(total / 12);

  return (
    <div className="container-page py-8">
      <header className="mb-8 flex flex-col items-start gap-4 border-b border-surface pb-8 sm:flex-row sm:items-center">
        {author.avatar ? (
          <Image src={getImageUrl(author.avatar)} alt={author.name} width={80} height={80} className="h-20 w-20 rounded-full object-cover" />
        ) : (
          <span className="grid h-20 w-20 flex-shrink-0 place-items-center rounded-full bg-brand-900 text-2xl font-bold text-white">
            {author.name?.[0]?.toUpperCase()}
          </span>
        )}
        <div>
          <p className="text-xs font-bold uppercase tracking-widest text-accent-500">{ROLE_LABEL[author.role] || 'Contributor'}</p>
          <h1 className="mt-1 font-serif text-3xl font-extrabold sm:text-4xl">{author.name}</h1>
          {author.bio && <p className="mt-2 max-w-2xl text-muted">{author.bio}</p>}
          <p className="mt-2 text-sm text-muted">{total} article{total !== 1 ? 's' : ''}</p>
        </div>
      </header>

      {articles.length === 0 ? (
        <p className="py-16 text-center text-muted">This author hasn&apos;t published any articles yet.</p>
      ) : (
        <div className="grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
          {articles.map((a: any) => (
            <ArticleCard key={a.id} article={a} />
          ))}
        </div>
      )}

      <Pagination page={page} totalPages={totalPages} makeHref={(p) => `?page=${p}`} />
    </div>
  );
}
