import { notFound } from "next/navigation";
import { readFile, readdir } from "node:fs/promises";
import { join } from "node:path";
import { parseMarkdownWithFrontmatter, Frontmatter } from "@/lib/markdown";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";

type Params = { params: Promise<{ slug: string }> };

async function getAvailableSlugs(): Promise<string[]> {
  try {
    const root = process.cwd();
    const dir = join(root, "content", "pt", "perguntas");
    const files = await readdir(dir);
    return files
      .filter((f) => f.endsWith(".md"))
      .map((f) => f.replace(/\.md$/, ""));
  } catch {
    return [];
  }
}

export async function generateStaticParams() {
  const slugs = await getAvailableSlugs();
  return slugs.map((slug) => ({
    slug,
  }));
}

export default async function FaqArticlePage({ params }: Params) {
  const { slug } = await params;
  const root = process.cwd();
  const file = join(root, "content", "pt", "perguntas", `${slug}.md`);
  try {
    const raw = await readFile(file);
    const { content, frontmatter: fm } = parseMarkdownWithFrontmatter(raw.toString());
    const frontmatter = fm as Frontmatter & { readTime?: string; intendedFor?: string; author?: string; authorImage?: string };
    return (
      <article aria-labelledby="article-title" className="max-w-3xl mx-auto">
        <header className="mb-8 pb-6 border-b border-gray-200">
          <h1 id="article-title" className="text-4xl font-bold mb-6 text-gray-900">
            {String(frontmatter.title ?? "FAQ")}
          </h1>

          {/* Metadata Grid */}
          <div className="grid grid-cols-2 md:grid-cols-3 gap-4 mb-6">
            {frontmatter.readTime && (
              <div>
                <p className="text-xs font-semibold text-gray-500 uppercase tracking-wide">
                  Tempo de Leitura
                </p>
                <p className="text-sm text-gray-700 mt-1">{String(frontmatter.readTime)}</p>
              </div>
            )}
            {frontmatter.intendedFor && (
              <div>
                <p className="text-xs font-semibold text-gray-500 uppercase tracking-wide">
                  Quem?
                </p>
                <p className="text-sm text-gray-700 mt-1">{String(frontmatter.intendedFor)}</p>
              </div>
            )}
          </div>

          {/* Author Section */}
          {frontmatter.author && (
            <div className="flex items-center gap-4 pt-4">
              {frontmatter.authorImage && (
                <img
                  src={String(frontmatter.authorImage)}
                  alt={String(frontmatter.author)}
                  className="w-16 h-16 rounded-full object-cover border-2 border-gray-200"
                />
              )}
              <div>
                <p className="text-xs font-semibold text-gray-500 uppercase tracking-wide">
                  Autor
                </p>
                <p className="text-sm font-semibold text-gray-900 mt-1">
                  {String(frontmatter.author)}
                </p>
              </div>
            </div>
          )}
        </header>

        <div className="prose prose-sm md:prose md:max-w-none text-gray-700">
          <ReactMarkdown remarkPlugins={[remarkGfm]}>{content}</ReactMarkdown>
        </div>
      </article>
    );
  } catch (e) {
    notFound();
  }
}
