import React from 'react'
import { Metadata } from 'next'
import { getLocale, getTranslations } from 'next-intl/server'
import { notFound } from 'next/navigation'
import GlossaireHero from '../components/GlossaireHero'
import GlossaireCTA from '../components/GlossaireCTA'
import GlossaireFilter from '../components/GlossaireFilter'
import GlossaireDetails from './components/GlossaireDetails'
import glossaryData from '@/utils/dadycar_glossary_final_152_terms.json'
import GlossaryTermStructuredData from './components/GlossaryTermStructuredData '

type Params = Promise<{ slug: string }>

// Generate static params for all glossary terms
export async function generateStaticParams() {
    const terms = glossaryData?.glossary?.terms || []

    return terms.flatMap(term => [
        { slug: term.slug_en },
        { slug: term.slug_fr }
    ])
}

export const generateMetadata = async (props: { params: Params }): Promise<Metadata> => {
    const locale = await getLocale()
    const params = await props.params

    // Find the glossary term
    const glossaryTerm = glossaryData?.glossary?.terms?.find(
        (term) => term?.slug_en === params.slug || term?.slug_fr === params.slug
    )

    // If term not found, return minimal metadata (404 page will handle display)
    if (!glossaryTerm) {
        return {
            title: locale === 'en' 
                ? 'Term Not Found | Dadycar Glossary' 
                : 'Terme Introuvable | Glossaire Dadycar',
            description: locale === 'en'
                ? 'The requested glossary term could not be found. Browse our complete fleet management glossary.'
                : 'Le terme recherché est introuvable. Parcourez notre glossaire complet de gestion de flotte.',
            robots: {
                index: false, // Don't index 404 pages
                follow: true,  // But follow links on the page
            }
        }
    }

    const name = locale === "en" ? glossaryTerm.name_en : glossaryTerm.name_fr
    const summary = locale === "en" ? glossaryTerm.summary_en : glossaryTerm.summary_fr
    const question = locale === "en" ? glossaryTerm.question_en : glossaryTerm.question_fr
    const category = locale === "en" ? glossaryTerm.category_en : glossaryTerm.category_fr

    const slug = locale === "en" ? glossaryTerm.slug_en : glossaryTerm.slug_fr
    const canonicalUrl = `${process.env.NEXT_PUBLIC_FRONTEND_HOST}${locale === 'en' ? '/en/glossary' : '/glossaire'}/${slug}`

    // Build keywords from the term's keywords array
    const keywords = glossaryTerm.keywords
        ?.map(k => locale === "en" ? k.keyword_en : k.keyword_fr)
        .join(', ') || ''

    const title = `${name} - ${locale === 'en' ? 'Fleet Management Glossary' : 'Glossaire Gestion de Flotte'} | Dadycar`
    const description = summary || question

    return {
        title,
        description,
        keywords: `${keywords}, ${name}, ${category}, fleet management, gestion de flotte`,
        openGraph: {
            title,
            description,
            url: canonicalUrl,
            type: 'article',
            siteName: 'Dadycar',
        },
        twitter: {
            card: 'summary_large_image',
            title,
            description,
        },
        alternates: {
            canonical: canonicalUrl,
            languages: {
                'fr': `${process.env.NEXT_PUBLIC_FRONTEND_HOST}/glossaire/${glossaryTerm.slug_fr}`,
                'en': `${process.env.NEXT_PUBLIC_FRONTEND_HOST}/en/glossary/${glossaryTerm.slug_en}`,
            },
        },
        robots: {
            index: true,
            follow: true,
        }
    }
}

const GlossaireDetailsPage = async (props: { params: Params }) => {
    const locale = await getLocale()
    const params = await props.params
    const t = await getTranslations()

    // Find the glossary term
    const glossaryTerm = glossaryData?.glossary?.terms?.find(
        (term) => term?.slug_en === params.slug || term?.slug_fr === params.slug
    )

    // If term not found, trigger Next.js 404 page
    // This returns proper 404 HTTP status code for SEO
    if (!glossaryTerm) {
        notFound()
    }

    // Extract all letters for filter
    const allLetters = glossaryData?.glossary?.terms?.map((term) =>
        locale === "en" ? term?.name_en?.charAt(0).toUpperCase() : term?.name_fr?.charAt(0).toUpperCase()
    )
    const uniqueLetters = [...new Set(allLetters)].sort()

    return (
        <main>
            {/* Add structured data for SEO */}
            <GlossaryTermStructuredData term={glossaryTerm} locale={locale} />

            <GlossaireHero
                title={locale === "en" ? glossaryTerm?.name_en : glossaryTerm?.name_fr}
                description={locale === "en" ? glossaryTerm?.summary_en : glossaryTerm?.summary_fr}
            />
            <div className="!mt-[60px] mb-[60px] max-w-full sm:max-w-[576px] md:max-w-[768px] lg:max-w-[992px] xl:max-w-[1200px] mx-auto space-y-[66px] lg:space-y-[80px] xl:space-y-[120px]">
                <div className="flex flex-col-reverse lg:flex-row gap-4">
                    <GlossaireFilter
                        isThereSearch={false}
                        letters={uniqueLetters}
                    />
                    <GlossaireDetails item={glossaryTerm} />
                </div>
            </div>
            <GlossaireCTA />
        </main>
    )
}

export default GlossaireDetailsPage