'use client'

import { createContext, useContext, useEffect, useMemo, useRef, useState } from 'react'
import { usePathname, useRouter } from 'next/navigation'
import { appPrivacyHref, appTermsHref, footerPageHref } from '@/lib/footerContent'
import { isCarplaceLanguage, type CarplaceLanguage } from '@/lib/i18n'
import { SHARED_LANGUAGE_KEY, SHARED_THEME_KEY, readScopedPreference, writeScopedPreference } from '@/lib/preferences'

type Theme = 'light' | 'dark'

export const localeOptions: Array<{ value: CarplaceLanguage; label: string; flag: string }> = [
  { value: 'en', label: 'English', flag: '🇬🇧' },
  { value: 'ar', label: 'العربية', flag: '🇲🇦' },
  { value: 'fr', label: 'Français', flag: '🇫🇷' },
]

type Dictionary = {
  home: string
  carplace: string
  signIn: string
  ownerSignIn: string
  language: string
  theme: string
  light: string
  dark: string
  preferences: string
}

const dictionaries: Record<CarplaceLanguage, Dictionary> = {
  en: {
    home: 'Home',
    carplace: 'Carplace',
    signIn: 'Sign in',
    ownerSignIn: 'Create Agency Space',
    language: 'Language',
    theme: 'Theme',
    light: 'Light',
    dark: 'Dark',
    preferences: 'Carplace preferences',
  },
  fr: {
    home: 'Accueil',
    carplace: 'Carplace',
    signIn: 'Connexion',
    ownerSignIn: "Créer un espace d'agence",
    language: 'Langue',
    theme: 'Mode',
    light: 'Clair',
    dark: 'Sombre',
    preferences: 'Préférences Carplace',
  },
  ar: {
    home: 'الرئيسية',
    carplace: 'السوق',
    signIn: 'تسجيل الدخول',
    ownerSignIn: 'إنشاء مساحة الوكالة',
    language: 'اللغة',
    theme: 'الوضع',
    light: 'فاتح',
    dark: 'داكن',
    preferences: 'تفضيلات Carplace',
  },
}

type FooterContent = {
  localeLabel: string
  rightsLabel: string
  primary: Array<{ label: string; href: string }>
  secondary: Array<{ label: string; href: string }>
}

const footerLabels: Record<CarplaceLanguage, FooterContent> = {
  en: {
    localeLabel: 'Global (English)',
    rightsLabel: 'All rights reserved.',
    primary: [
      { label: 'Privacy Policy', href: appPrivacyHref.en },
      { label: 'Terms of Use', href: appTermsHref.en },
      { label: 'Security', href: footerPageHref.security },
    ],
    secondary: [
      { label: 'About Us', href: footerPageHref['about-us'] },
      { label: 'Contact Sales', href: footerPageHref['contact-sales'] },
      { label: 'Cookie Policy', href: footerPageHref['cookie-policy'] },
    ],
  },
  fr: {
    localeLabel: 'Europe (French)',
    rightsLabel: 'Tous droits réservés.',
    primary: [
      { label: 'Politique de confidentialité', href: appPrivacyHref.fr },
      { label: "Conditions d'utilisation", href: footerPageHref['terms-of-service'] },
      { label: 'Sécurité', href: footerPageHref.security },
    ],
    secondary: [
      { label: 'À propos', href: footerPageHref['about-us'] },
      { label: 'Contact commercial', href: footerPageHref['contact-sales'] },
      { label: 'Conditions générales', href: footerPageHref['general-conditions'] },
    ],
  },
  ar: {
    localeLabel: 'North Africa (Arabic)',
    rightsLabel: 'جميع الحقوق محفوظة.',
    primary: [
      { label: 'سياسة الخصوصية', href: appPrivacyHref.ar },
      { label: 'شروط الاستخدام', href: appTermsHref.ar },
      { label: 'الأمان', href: footerPageHref.security },
    ],
    secondary: [
      { label: 'من نحن', href: footerPageHref['about-us'] },
      { label: 'تواصل مع المبيعات', href: footerPageHref['contact-sales'] },
      { label: 'الشروط العامة', href: footerPageHref['general-conditions'] },
    ],
  },
}

export function getFooterContent(language: CarplaceLanguage): FooterContent {
  return footerLabels[language]
}

function detectBrowserLanguage(): CarplaceLanguage | null {
  if (typeof navigator === 'undefined') return null
  for (const language of Array.from(navigator.languages ?? [navigator.language])) {
    const code = language.split('-')[0].toLowerCase()
    if (isCarplaceLanguage(code)) return code
  }
  return null
}

type PreferencesContextValue = {
  language: CarplaceLanguage
  theme: Theme
  dict: Dictionary
  setLanguage: (language: CarplaceLanguage) => void
  setTheme: (theme: Theme) => void
}

const PreferencesContext = createContext<PreferencesContextValue | null>(null)

export function useCarplacePreferences() {
  const context = useContext(PreferencesContext)
  if (!context) throw new Error('useCarplacePreferences must be used within CarplaceShell')
  return context
}

export default function CarplaceShell({
  children,
  initialLanguage = 'en',
  initialTheme = 'light',
}: {
  children: React.ReactNode
  initialLanguage?: CarplaceLanguage
  initialTheme?: Theme
}) {
  const router = useRouter()
  const pathname = usePathname()
  const [language, setLanguageState] = useState<CarplaceLanguage>(initialLanguage)
  const [theme, setThemeState] = useState<Theme>(initialTheme)
  const [hydrated, setHydrated] = useState(false)
  const previousLanguage = useRef<CarplaceLanguage>(initialLanguage)

  function applyLanguage(nextLanguage: CarplaceLanguage) {
    if (typeof window !== 'undefined') {
      document.documentElement.lang = nextLanguage
      document.documentElement.dir = nextLanguage === 'ar' ? 'rtl' : 'ltr'
      writeScopedPreference(SHARED_LANGUAGE_KEY, nextLanguage)
    }
    setLanguageState(nextLanguage)
  }

  function applyTheme(nextTheme: Theme) {
    if (typeof window !== 'undefined') {
      document.documentElement.classList.toggle('dark', nextTheme === 'dark')
      document.documentElement.style.colorScheme = nextTheme
      document.body.dataset.theme = nextTheme
      writeScopedPreference(SHARED_THEME_KEY, nextTheme)
    }
    setThemeState(nextTheme)
  }

  useEffect(() => {
    const storedLanguage = readScopedPreference(SHARED_LANGUAGE_KEY)
    const resolvedLanguage = isCarplaceLanguage(storedLanguage) ? storedLanguage : detectBrowserLanguage()
    if (resolvedLanguage) setLanguageState(resolvedLanguage)

    const storedTheme = readScopedPreference(SHARED_THEME_KEY)
    if (storedTheme === 'light' || storedTheme === 'dark') setThemeState(storedTheme)
    setHydrated(true)
  }, [])

  useEffect(() => {
    document.documentElement.lang = language
    document.documentElement.dir = language === 'ar' ? 'rtl' : 'ltr'
    if (!hydrated) return
    writeScopedPreference(SHARED_LANGUAGE_KEY, language)
    if (previousLanguage.current !== language) router.refresh()
    previousLanguage.current = language
  }, [hydrated, language, pathname, router])

  useEffect(() => {
    document.documentElement.classList.toggle('dark', theme === 'dark')
    document.documentElement.style.colorScheme = theme
    document.body.dataset.theme = theme
    if (hydrated) writeScopedPreference(SHARED_THEME_KEY, theme)
  }, [hydrated, theme])

  const value = useMemo(
    () => ({ language, theme, dict: dictionaries[language], setLanguage: applyLanguage, setTheme: applyTheme }),
    [language, theme],
  )

  return <PreferencesContext.Provider value={value}>{children}</PreferencesContext.Provider>
}
