'use client';

import React, { createContext, useContext, useEffect, useState } from 'react';
import { usePathname } from 'next/navigation';

type Language = 'es' | 'en';

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

interface LanguageContextType {
  language: Language;
  setLanguage: (lang: Language) => void;
  t: (key: string) => string;
  isLoaded: boolean;
}

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

const defaultTranslations = {
  es: { common: { loading: 'Cargando...' } } as Translations,
  en: { common: { loading: 'Loading...' } } as Translations,
};

export function LanguageProvider({ children }: { children: React.ReactNode }) {
  const [language, setLanguageState] = useState<Language>('es');
  const [isLoaded, setIsLoaded] = useState(false);
  const [translations, setTranslations] = useState(defaultTranslations);
  const pathname = usePathname();

  useEffect(() => {
    // Load translations and language preference on mount
    const loadLanguageSettings = async () => {
      try {
        // Load translation files
        const [esModule, enModule] = await Promise.all([
          import('@/messages/es.json'),
          import('@/messages/en.json'),
        ]);

        const esTranslations = esModule.default || esModule;
        const enTranslations = enModule.default || enModule;

        setTranslations({
          es: esTranslations,
          en: enTranslations,
        });

        // Get language preference from localStorage or user profile
        const savedLanguage = localStorage.getItem('language') as Language | null;
        if (savedLanguage && (savedLanguage === 'es' || savedLanguage === 'en')) {
          setLanguageState(savedLanguage);
          document.documentElement.lang = savedLanguage;
        } else {
          // Default to Spanish
          setLanguageState('es');
          document.documentElement.lang = 'es';
          localStorage.setItem('language', 'es'); // Force save default
        }

        setIsLoaded(true);
      } catch (error) {
        console.error('Error loading language settings:', error);
        setIsLoaded(true);
      }
    };

    loadLanguageSettings();
  }, []);

  useEffect(() => {
    if (!isLoaded) return;
    const localizedTitle = translations[language]?.app?.title;
    document.title = typeof localizedTitle === 'string'
      ? localizedTitle
      : (translations.es?.app?.title || 'Medklinix');
  }, [language, isLoaded, translations, pathname]);

  const setLanguage = (lang: Language) => {
    setLanguageState(lang);
    localStorage.setItem('language', lang);
    document.documentElement.lang = lang;
  };

  const t = (key: string): string => {
    const keys = key.split('.');
    const dict = translations[language];

    if (!dict) {
      return key;
    }

    let value: any = dict;
    for (const k of keys) {
      if (value && typeof value === 'object' && k in value) {
        value = value[k];
      } else {
        return key; // Return the key if not found
      }
    }

    return typeof value === 'string' ? value : key;
  };

  if (!isLoaded) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">
            {translations[language]?.common?.loading || translations.es?.common?.loading || translations.en?.common?.loading || 'Loading...'}
          </p>
        </div>
      </div>
    );
  }

  return (
    <LanguageContext.Provider value={{ language, setLanguage, t, isLoaded }}>
      {children}
    </LanguageContext.Provider>
  );
}

export function useLanguage() {
  const context = useContext(LanguageContext);
  if (context === undefined) {
    // Return a default context for cases where the hook is used outside provider
    // This prevents errors during static generation
    return {
      language: 'es' as Language,
      setLanguage: () => { },
      t: (key: string) => key,
      isLoaded: false,
    };
  }
  return context;
}
