import React, { createContext, useContext, useState, useEffect, useCallback, ReactNode } from 'react';
import en from '../locales/en.json';
import ar from '../locales/ar.json';

type LanguageCode = 'en' | 'ar';
type Direction = 'ltr' | 'rtl';

interface Translations {
  [key: string]: string | Translations;
}

const translations: Record<LanguageCode, Translations> = { en, ar };

interface LanguageContextType {
  lang: LanguageCode;
  dir: Direction;
  t: (key: string, fallback?: string) => string;
  switchLanguage: () => void;
  setLanguage: (lang: LanguageCode) => void;
}

const LanguageContext = createContext<LanguageContextType | null>(null);

interface LanguageProviderProps {
  children: ReactNode;
}

export function LanguageProvider({ children }: LanguageProviderProps) {
  const [lang, setLang] = useState<LanguageCode>(() => {
    // Check localStorage first, then browser preference
    const saved = localStorage.getItem('hihala-lang') as LanguageCode | null;
    if (saved && translations[saved]) return saved;
    
    // Check browser language
    const browserLang = navigator.language?.split('-')[0];
    if (browserLang === 'ar') return 'ar';
    return 'en';
  });

  const dir: Direction = lang === 'ar' ? 'rtl' : 'ltr';

  // Apply direction to document
  useEffect(() => {
    document.documentElement.dir = dir;
    document.documentElement.lang = lang;
    localStorage.setItem('hihala-lang', lang);
  }, [lang, dir]);

  // Translation function with dot notation support
  const t = useCallback((key: string, fallback?: string): string => {
    const keys = key.split('.');
    let value: Translations | string = translations[lang];
    
    for (const k of keys) {
      if (value && typeof value === 'object' && k in value) {
        value = value[k];
      } else {
        // Try English fallback
        value = translations.en;
        for (const ek of keys) {
          if (value && typeof value === 'object' && ek in value) {
            value = value[ek];
          } else {
            return fallback || key;
          }
        }
        break;
      }
    }
    
    return typeof value === 'string' ? value : (fallback || key);
  }, [lang]);

  // Switch language
  const switchLanguage = useCallback(() => {
    setLang(prev => prev === 'en' ? 'ar' : 'en');
  }, []);

  // Set specific language
  const setLanguage = useCallback((newLang: LanguageCode) => {
    if (translations[newLang]) {
      setLang(newLang);
    }
  }, []);

  return (
    <LanguageContext.Provider value={{ lang, dir, t, switchLanguage, setLanguage }}>
      {children}
    </LanguageContext.Provider>
  );
}

export function useLanguage(): LanguageContextType {
  const context = useContext(LanguageContext);
  if (!context) {
    throw new Error('useLanguage must be used within a LanguageProvider');
  }
  return context;
}

export default LanguageContext;
