import React from 'react'
import { Metadata } from 'next'
import { getLocale, getTranslations } from 'next-intl/server'
import GlossaireCTA from "./components/GlossaireCTA"
import GlossaireFilter from "./components/GlossaireFilter"
import GlossaireHero from "./components/GlossaireHero"
import GlossaireItems from "./components/GlossaireItems"

import glossaryData from '@/utils/dadycar_glossary_final_152_terms.json'
import { getGlossaryMeta } from '@/components/metaData'
export const generateMetadata = async (): Promise<Metadata> => {
  const t = await getTranslations('')
  return await getGlossaryMeta(t)
}

type SearchParams = Promise<{ 
  category?: string
  search?: string
  letter?: string
  innovation?: string
}>

const GlossairePage = async (props: { searchParams: SearchParams }) => {
  const t = await getTranslations()
  const locale = await getLocale()
  const searchParams = await props.searchParams

  // Extract all letters from glossary terms 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()

  // Get search params for filtering
  const category = searchParams?.category
  const search = searchParams?.search
  const letter = searchParams?.letter
  const innovation = searchParams?.innovation

  // Server-side filtering for initial render and SEO
  const filteredGlossaries = glossaryData?.glossary?.terms?.filter((term) =>
    (category ? (locale === "en" ? term?.category_en === category : term?.category_fr === category) : true)
    && (search ? (locale === "en" 
      ? term?.name_en?.toLowerCase()?.includes(search?.toLowerCase()) 
      : term?.name_fr?.toLowerCase()?.includes(search?.toLowerCase())) : true)
    && (innovation === 'true' ? term?.innovation === true : true)
    && (letter ? (locale === "en" 
      ? term?.name_en?.toUpperCase().startsWith(letter.toUpperCase()) 
      : term?.name_fr?.toUpperCase().startsWith(letter.toUpperCase())) : true)
  )

  return (
    <main className="overflow-visible">
      <GlossaireHero 
        title={t("Intelligent Fleet Management Glossary")}
        description={t("The most comprehensive reference guide to technical terms in fleet management with artificial intelligence, predictive maintenance, and advanced technologies")}
      />
      <div className="mt-[30px] lg: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 lg:flex-row gap-4">
          <GlossaireFilter 
            letters={uniqueLetters}
          />
          <GlossaireItems 
            glossaries={filteredGlossaries}
          />
        </div>
      </div>
      <GlossaireCTA />
    </main>
  )
}

export default GlossairePage