import { AboutSection } from '@/components/aboutpage/aboutsection'
import { getAboutFields, getAboutPage, type SiteLanguage } from '@/lib/api'
import type { AboutFields } from '@/types/about'
import type { Metadata } from 'next'
import { unstable_rethrow } from 'next/navigation'

interface AboutPageProps {
  searchParams: Promise<{ lang?: string | string[] }>
}

function getLanguage(value: string | string[] | undefined): SiteLanguage {
  const lang = Array.isArray(value) ? value[0] : value

  return lang === 'ps' || lang === 'dr' ? lang : 'en'
}

const fallbackImage = { url: '', alt: '', width: 1, height: 1 }

const fallbackAboutFields: AboutFields = {
  banner_title: 'About <span>PayseyPay</span>',
  banner_description: 'Payment solutions built for everyday people, businesses, and communities.',
  banner_bg_image: fallbackImage,
  banner_bg_image_2: fallbackImage,
  mission_list: [],
  why_paysey_badge_text: '',
  why_paysey_section_title: '',
  why_paysey_description: '',
  why_paysey_list: [],
  trust_badge_text: '',
  trust_section_title: '',
  trust_description: '',
  trust_section_image: fallbackImage,
  ecosystem_badge_title: '',
  ecosystem_section_title: '',
  ecosystem_description: '',
  ecosystem_list: [],
  faqs_badge_title: '',
  faqs_section_title: '',
  faqs_description: '',
  faqs_list: [],
  cta_title: '',
  cta_description: '',
  cta_button_text: '',
  button_url: '',
  cta_logo: fallbackImage,
  contact_badge_text: '',
  contact_section_title: '',
  contact_description: '',
  contact_info_list: [],
  contact_form_title: '',
  contact_form_description: '',
  form_fields_label: [],
  submit_button_text: '',
}

export async function generateMetadata({ searchParams }: AboutPageProps): Promise<Metadata> {
  try {
    const { lang } = await searchParams
    const data = await getAboutPage(getLanguage(lang))

    return {
      title: data.seo.meta_title || data.title,
      description: data.seo.meta_description || undefined,
      keywords: data.seo.focus_keyword || undefined,
    }
  } catch (error) {
    unstable_rethrow(error)
    return {}
  }
}

export default async function AboutPage({ searchParams }: AboutPageProps) {
  let fields = fallbackAboutFields

  try {
    const { lang } = await searchParams
    const data = await getAboutPage(getLanguage(lang))
    fields = getAboutFields(data)
  } catch (error) {
    unstable_rethrow(error)
    console.error('Unable to load about page API data.', error)
  }

  return <AboutSection fields={fields} />
}
