import { notFound } from "next/navigation";
import { Metadata } from "next";
import Link from "next/link";
import {
  SITE_URL,
  COMPANY_NAME,
  COMPANY_PHONE,
  WHATSAPP_URL,
} from "@/data/services";
import { getArticleBySlug, getAllArticleSlugs } from "@/data/articles";
import CTASection from "@/components/CTASection";
import Button from "@/components/Button";

interface PageProps {
  params: Promise<{ slug: string }>;
}

export async function generateStaticParams() {
  const articles = await import("@/data/articles").then((m) =>
    m.getAllArticleSlugs(),
  );
  return articles.map((slug) => ({ slug }));
}

export async function generateMetadata({
  params,
}: PageProps): Promise<Metadata> {
  const { slug } = await params;
  const article = getArticleBySlug(slug);

  if (!article) return {};

  return {
    title: article.title,
    description: article.description,
    keywords: article.seo.keywords,
    alternates: { canonical: `/recursos/${slug}` },
    openGraph: {
      title: `${article.title} | ${COMPANY_NAME}`,
      description: article.description,
      url: `${SITE_URL}/recursos/${slug}`,
      type: "article",
      publishedTime: article.publishedAt,
      authors: [article.author],
    },
  };
}

export default async function ArticlePage({ params }: PageProps) {
  const { slug } = await params;
  const article = getArticleBySlug(slug);

  if (!article) {
    notFound();
  }

  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "NewsArticle",
    headline: article.title,
    description: article.description,
    datePublished: article.publishedAt,
    author: {
      "@type": "Organization",
      name: COMPANY_NAME,
      url: SITE_URL,
    },
    publisher: {
      "@type": "Organization",
      name: COMPANY_NAME,
      url: SITE_URL,
    },
    image: `${SITE_URL}/images/about.webp`,
  };

  // Add FAQ schema if available
  const faqSchema =
    article.seo.faqSchema && article.seo.faqSchema.length > 0
      ? {
          "@context": "https://schema.org",
          "@type": "FAQPage",
          mainEntity: article.seo.faqSchema.map((faq) => ({
            "@type": "Question",
            name: faq.question,
            acceptedAnswer: {
              "@type": "Answer",
              text: faq.answer,
            },
          })),
        }
      : null;

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />
      {faqSchema && (
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(faqSchema) }}
        />
      )}

      <h1 className="sr-only">{article.title}</h1>

      {/* Hero Section */}
      <section className="bg-primary text-white py-10 md:py-16 px-4">
        <div className="max-w-3xl mx-auto">
          <nav className="mb-6">
            <Link href="/recursos" className="text-sm hover:underline">
              ← Voltar para Recursos
            </Link>
          </nav>
          <h1 className="text-3xl md:text-4xl font-bold mb-4">
            {article.title}
          </h1>
          <p className="text-lg opacity-90">{article.description}</p>
          <div className="mt-6 flex items-center gap-4 text-sm">
            <span>{article.author}</span>
            <span>•</span>
            <time dateTime={article.publishedAt}>
              {new Date(article.publishedAt).toLocaleDateString("pt-BR", {
                year: "numeric",
                month: "long",
                day: "numeric",
              })}
            </time>
          </div>
        </div>
      </section>

      {/* Article Content */}
      <article className="max-w-3xl mx-auto py-12 md:py-16 px-4">
        <div className="prose prose-lg max-w-none">
          {article.content.map((section, index) => (
            <div key={index} className="mb-8">
              <h2 className="text-2xl font-bold text-primary mb-4">
                {section.heading}
              </h2>
              <p className="text-text leading-relaxed text-lg">
                {section.text}
              </p>
            </div>
          ))}
        </div>

        {/* FAQ Section if available */}
        {article.seo.faqSchema && article.seo.faqSchema.length > 0 && (
          <section className="mt-16 pt-12 border-t border-gray-200">
            <h2 className="text-2xl font-bold text-primary mb-8">
              Perguntas Frequentes
            </h2>
            <div className="space-y-6">
              {article.seo.faqSchema.map((faq, index) => (
                <details
                  key={index}
                  className="group border border-gray-200 rounded-lg p-6 cursor-pointer hover:bg-gray-50">
                  <summary className="font-semibold text-primary text-lg list-none">
                    <span className="mr-2 text-2xl group-open:hidden">+</span>
                    <span className="hidden mr-2 text-2xl group-open:inline">
                      −
                    </span>
                    {faq.question}
                  </summary>
                  <p className="mt-4 text-text leading-relaxed">{faq.answer}</p>
                </details>
              ))}
            </div>
          </section>
        )}

        {/* CTA Section */}
        <section className="mt-16 pt-12 border-t border-gray-200 bg-gray-light rounded-lg p-8 text-center">
          <h3 className="text-2xl font-bold text-primary mb-4">
            Precisa de Ajuda?
          </h3>
          <p className="text-text mb-6 max-w-xl mx-auto">
            A Kontec Engenharia oferece consultoria especializada em segurança
            contra incêndio e sistemas de proteção. Entre em contato conosco
            para uma avaliação gratuita.
          </p>
          <div className="flex flex-col sm:flex-row gap-4 justify-center">
            <a href={WHATSAPP_URL} target="_blank" rel="noopener noreferrer">
              <Button>Falar no WhatsApp</Button>
            </a>
          </div>
        </section>
      </article>

      {/* Related Articles Section */}
      <CTASection />
    </>
  );
}
