'use client'

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

export type AdminLanguage = 'en' | 'fr' | 'ar'
export type AdminTheme = 'light' | 'dark'

type AdminDictionary = {
  nav: Record<string, string>
  logout: string
  language: string
  theme: string
  light: string
  dark: string
  overview: string
  admin: string
  platform: string
  loading: string
}

const dictionaries: Record<AdminLanguage, AdminDictionary> = {
  en: {
    nav: {
      overview: 'Overview',
      companies: 'Companies',
      siteConfig: 'Site Config',
      renters: 'Renters',
      auditLogs: 'Audit Logs',
      adminUsers: 'Admin Users',
      billing: 'Billing',
    },
    logout: 'Logout',
    language: 'Language',
    theme: 'Theme',
    light: 'Light',
    dark: 'Dark',
    overview: 'Platform overview',
    admin: 'Admin',
    platform: 'Platform',
    loading: 'Loading',
  },
  fr: {
    nav: {
      overview: "Vue d'ensemble",
      companies: 'Entreprises',
      siteConfig: 'Config site',
      renters: 'Locataires',
      auditLogs: "Journaux d'audit",
      adminUsers: 'Utilisateurs admin',
      billing: 'Facturation',
    },
    logout: 'Déconnexion',
    language: 'Langue',
    theme: 'Mode',
    light: 'Clair',
    dark: 'Sombre',
    overview: 'Vue plateforme',
    admin: 'Admin',
    platform: 'Plateforme',
    loading: 'Chargement',
  },
  ar: {
    nav: {
      overview: 'نظرة عامة',
      companies: 'الشركات',
      siteConfig: 'إعدادات الموقع',
      renters: 'المستأجرون',
      auditLogs: 'سجلات التدقيق',
      adminUsers: 'مستخدمو الإدارة',
      billing: 'الفوترة',
    },
    logout: 'تسجيل الخروج',
    language: 'اللغة',
    theme: 'الوضع',
    light: 'فاتح',
    dark: 'داكن',
    overview: 'نظرة عامة على المنصة',
    admin: 'الإدارة',
    platform: 'المنصة',
    loading: 'جارٍ التحميل',
  },
}

type AdminI18nContext = {
  language: AdminLanguage
  setLanguage: (value: AdminLanguage) => void
  theme: AdminTheme
  setTheme: (value: AdminTheme) => void
  dict: AdminDictionary
}

const Context = createContext<AdminI18nContext | null>(null)

export function AdminI18nProvider({ children }: { children: React.ReactNode }) {
  const [language, setLanguage] = useState<AdminLanguage>('en')
  const [theme, setTheme] = useState<AdminTheme>('dark')

  useEffect(() => {
    const stored = window.localStorage.getItem('admin-language')
    const storedTheme = window.localStorage.getItem('admin-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('light')
    }
  }, [])

  useEffect(() => {
    document.documentElement.lang = language
    document.documentElement.dir = language === 'ar' ? 'rtl' : 'ltr'
    window.localStorage.setItem('admin-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('admin-theme', theme)
  }, [theme])

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

export function useAdminI18n() {
  const context = useContext(Context)
  if (!context) throw new Error('useAdminI18n must be used within AdminI18nProvider')
  return context
}

export function AdminLanguageSwitcher() {
  const { language, setLanguage, dict } = useAdminI18n()
  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-zinc-700 bg-zinc-900 px-2 py-1 shadow-sm transition-colors">
      <span className="px-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-zinc-500">{dict.language}</span>
      {(['en', 'fr', 'ar'] as AdminLanguage[]).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-zinc-100 text-zinc-950' : 'text-zinc-300 hover:bg-zinc-800'
            }`}
          >
            {value.toUpperCase()}
          </button>
        )
      })}
    </div>
  )
}

export function AdminThemeSwitcher() {
  const { theme, setTheme, dict } = useAdminI18n()
  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-zinc-700 bg-zinc-900 px-2 py-1 shadow-sm transition-colors">
      <span className="px-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-zinc-500">
        {dict.theme}
      </span>
      {(['light', 'dark'] as AdminTheme[]).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-zinc-100 text-zinc-950' : 'text-zinc-300 hover:bg-zinc-800'
            }`}
          >
            {value === 'light' ? dict.light : dict.dark}
          </button>
        )
      })}
    </div>
  )
}
