'use client'

import { createContext, useContext, useEffect, useMemo, useState } from 'react'

export type DashboardLanguage = 'en' | 'fr' | 'ar'
export type DashboardTheme = 'light' | 'dark'

type DashboardDictionary = {
  nav: Record<string, string>
  titles: Record<string, string>
  notifications: string
  noNewNotifications: string
  unreadNotifications: (count: number) => string
  signOut: string
  workspaceUser: string
  localAuth: string
  language: string
  theme: string
  light: string
  dark: string
}

const dictionaries: Record<DashboardLanguage, DashboardDictionary> = {
  en: {
    nav: {
      dashboard: 'Dashboard',
      fleet: 'Fleet',
      reservations: 'Reservations',
      onlineReservations: 'Online Reservations',
      customers: 'Customers',
      offers: 'Offers',
      team: 'Team',
      reports: 'Reports',
      billing: 'Billing',
      notifications: 'Notifications',
      settings: 'Settings',
    },
    titles: {
      '/dashboard': 'Dashboard',
      '/dashboard/fleet': 'Fleet Management',
      '/dashboard/reservations': 'Reservations',
      '/dashboard/online-reservations': 'Online Reservations',
      '/dashboard/customers': 'Customers',
      '/dashboard/offers': 'Offers',
      '/dashboard/team': 'Team',
      '/dashboard/reports': 'Reports',
      '/dashboard/billing': 'Billing',
      '/dashboard/settings': 'Settings',
    },
    notifications: 'Notifications',
    noNewNotifications: 'No new notifications',
    unreadNotifications: (count) => `${count} unread notification${count > 1 ? 's' : ''}`,
    signOut: 'Sign out',
    workspaceUser: 'Workspace user',
    localAuth: 'Local authentication',
    language: 'Language',
    theme: 'Theme',
    light: 'Light',
    dark: 'Dark',
  },
  fr: {
    nav: {
      dashboard: 'Tableau de bord',
      fleet: 'Flotte',
      reservations: 'Réservations',
      onlineReservations: 'Réservations en ligne',
      customers: 'Clients',
      offers: 'Offres',
      team: 'Équipe',
      reports: 'Rapports',
      billing: 'Facturation',
      notifications: 'Notifications',
      settings: 'Paramètres',
    },
    titles: {
      '/dashboard': 'Tableau de bord',
      '/dashboard/fleet': 'Gestion de flotte',
      '/dashboard/reservations': 'Réservations',
      '/dashboard/online-reservations': 'Réservations en ligne',
      '/dashboard/customers': 'Clients',
      '/dashboard/offers': 'Offres',
      '/dashboard/team': 'Équipe',
      '/dashboard/reports': 'Rapports',
      '/dashboard/billing': 'Facturation',
      '/dashboard/settings': 'Paramètres',
    },
    notifications: 'Notifications',
    noNewNotifications: 'Aucune nouvelle notification',
    unreadNotifications: (count) => `${count} notification${count > 1 ? 's' : ''} non lue${count > 1 ? 's' : ''}`,
    signOut: 'Déconnexion',
    workspaceUser: 'Utilisateur espace',
    localAuth: 'Authentification locale',
    language: 'Langue',
    theme: 'Mode',
    light: 'Clair',
    dark: 'Sombre',
  },
  ar: {
    nav: {
      dashboard: 'لوحة التحكم',
      fleet: 'الأسطول',
      reservations: 'الحجوزات',
      onlineReservations: 'الحجوزات الإلكترونية',
      customers: 'العملاء',
      offers: 'العروض',
      team: 'الفريق',
      reports: 'التقارير',
      billing: 'الفوترة',
      notifications: 'الإشعارات',
      settings: 'الإعدادات',
    },
    titles: {
      '/dashboard': 'لوحة التحكم',
      '/dashboard/fleet': 'إدارة الأسطول',
      '/dashboard/reservations': 'الحجوزات',
      '/dashboard/online-reservations': 'الحجوزات الإلكترونية',
      '/dashboard/customers': 'العملاء',
      '/dashboard/offers': 'العروض',
      '/dashboard/team': 'الفريق',
      '/dashboard/reports': 'التقارير',
      '/dashboard/billing': 'الفوترة',
      '/dashboard/settings': 'الإعدادات',
    },
    notifications: 'الإشعارات',
    noNewNotifications: 'لا توجد إشعارات جديدة',
    unreadNotifications: (count) => `${count} إشعار غير مقروء`,
    signOut: 'تسجيل الخروج',
    workspaceUser: 'مستخدم مساحة العمل',
    localAuth: 'مصادقة محلية',
    language: 'اللغة',
    theme: 'الوضع',
    light: 'فاتح',
    dark: 'داكن',
  },
}

type I18nContextValue = {
  language: DashboardLanguage
  setLanguage: (value: DashboardLanguage) => void
  theme: DashboardTheme
  setTheme: (value: DashboardTheme) => void
  dict: DashboardDictionary
}

const I18nContext = createContext<I18nContextValue | null>(null)

export function DashboardI18nProvider({ children }: { children: React.ReactNode }) {
  const [language, setLanguage] = useState<DashboardLanguage>('en')
  const [theme, setTheme] = useState<DashboardTheme>('light')

  useEffect(() => {
    const stored = window.localStorage.getItem('dashboard-language')
    const storedTheme = window.localStorage.getItem('dashboard-theme')

    if (stored === 'en' || stored === 'fr' || stored === 'ar') {
      setLanguage(stored)
    }

    if (storedTheme === 'light' || storedTheme === 'dark') {
      setTheme(storedTheme)
      return
    }

    if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
      setTheme('dark')
    }
  }, [])

  useEffect(() => {
    document.documentElement.lang = language
    document.documentElement.dir = language === 'ar' ? 'rtl' : 'ltr'
    window.localStorage.setItem('dashboard-language', language)
  }, [language])

  useEffect(() => {
    document.documentElement.classList.remove('light', 'dark')
    document.documentElement.classList.add(theme)
    document.documentElement.style.colorScheme = theme
    document.body.dataset.theme = theme
    window.localStorage.setItem('dashboard-theme', theme)
  }, [theme])

  const value = useMemo(
    () => ({ language, setLanguage, theme, setTheme, dict: dictionaries[language] }),
    [language, theme],
  )
  return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>
}

export function useDashboardI18n() {
  const context = useContext(I18nContext)
  if (!context) throw new Error('useDashboardI18n must be used within DashboardI18nProvider')
  return context
}

export function DashboardLanguageSwitcher() {
  const { language, setLanguage, dict } = useDashboardI18n()
  const [embedded, setEmbedded] = useState(false)

  useEffect(() => {
    setEmbedded(window.self !== window.top)
  }, [])

  if (embedded) return null

  return (
    <div className="flex items-center gap-1 rounded-full border border-slate-200 bg-white px-2 py-1 shadow-sm transition-colors dark:border-slate-700 dark:bg-slate-900">
      <span className="px-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">
        {dict.language}
      </span>
      {(['en', 'fr', 'ar'] as DashboardLanguage[]).map((value) => {
        const active = value === language
        return (
          <button
            key={value}
            type="button"
            onClick={() => setLanguage(value)}
            className={`rounded-full px-3 py-1.5 text-xs font-semibold transition ${
              active
                ? 'bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-950'
                : 'text-slate-600 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800'
            }`}
          >
            {value.toUpperCase()}
          </button>
        )
      })}
    </div>
  )
}

export function DashboardThemeSwitcher() {
  const { theme, setTheme, dict } = useDashboardI18n()
  const [embedded, setEmbedded] = useState(false)

  useEffect(() => {
    setEmbedded(window.self !== window.top)
  }, [])

  if (embedded) return null

  return (
    <div className="flex items-center gap-1 rounded-full border border-slate-200 bg-white px-2 py-1 shadow-sm transition-colors dark:border-slate-700 dark:bg-slate-900">
      <span className="px-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500 dark:text-slate-400">
        {dict.theme}
      </span>
      {(['light', 'dark'] as DashboardTheme[]).map((value) => {
        const active = value === theme
        return (
          <button
            key={value}
            type="button"
            onClick={() => setTheme(value)}
            className={`rounded-full px-3 py-1.5 text-xs font-semibold transition ${
              active
                ? 'bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-950'
                : 'text-slate-600 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800'
            }`}
          >
            {value === 'light' ? dict.light : dict.dark}
          </button>
        )
      })}
    </div>
  )
}
