import React, { createContext, useContext, useState, useEffect } from 'react';
import { Platform } from 'react-native';
import { storage } from '../utils/storage';
import { useAppConfig } from './ConfigContext';

export type LanguageType = 'English' | 'Indonesian';

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

export const translations: Translations = {
  English: {
    // Auth
    login: 'Login Now',
    register: 'Register Now',
    createAccount: 'Create New Account',
    registerSubtitle: 'Join us to start managing your workspace efficiently.',
    email: 'Email Address',
    password: 'Password',
    fullName: 'Full Name',
    forgotPass: 'Forgot Password?',
    rememberMe: 'Remember Me',
    noAccount: "Don't have an account? ",
    haveAccount: 'Already have an account? ',
    loginJust: 'Login Now',
    termsText: 'By registering, you agree to our ',
    termsLink: 'Terms of Service',
    privacyLink: 'Privacy Policy',
    and: ' and ',
    
    // Auth Extra
    signIn: 'Sign In',
    emailPlaceholder: 'email@example.com',
    passwordPlaceholder: '••••••••',
    signInNow: 'Sign In Now',
    orContinueWith: 'OR CONTINUE WITH',
    signUp: 'Sign Up',
    google: 'Google',
    apple: 'Apple',
    welcomeBack: 'Welcome back!',
    invalidEmail: 'Invalid email address',
    loginFailed: 'Login failed. Please try again.',
    bioConfirm: 'Confirm Identity',
    bioFailed: 'Biometric authentication failed',
    bioSuccess: 'Biometric Login Successful!',
    
    // Auth Extra 2
    fillAll: 'Please fill all required fields',
    passMismatch: 'Passwords do not match',
    accountCreated: 'Account created successfully!',
    confirmPassword: 'Confirm Password',
    namePlaceholder: 'John Doe',
    registering: 'Creating account...',
    
    // Profile Extra
    uploadingAvatar: 'Uploading avatar...',
    avatarUpdated: 'Profile picture updated!',
    profileUpdated: 'Profile updated successfully!',
    logoutSafe: 'Signing out safely...',
    confirmLogout: 'Are you sure you want to log out?',
    cancel: 'Cancel',
    logout: 'Logout',
    accCreated: 'Account created successfully!',
    regFailed: 'Registration failed',
    join: 'Join',
    confirmPass: 'Confirm Password',
    
    // Dashboard
    halo: 'Hello',
    role: 'Your Role: ',
    lastStatus: 'Last Status: ',
    history: 'Recent Activity',
    searchPlaceholder: 'Search items or locations...',
    loadMore: 'Load More',
    all: 'All',
    pending: 'Pending',
    completed: 'Success',
    high: 'Urgent',
    searching: 'Searching server...',

    // Dashboard Extra
    systemSupport: 'System Support',
    instantHelp: 'Instant Help 24/7',
    getHelp: 'Get Help',
    quickActions: 'Quick Actions',
    categories: 'Categories',
    latestDiscoveries: 'Latest Discoveries',
    account: 'Account',
    subscription: 'Subscription',
    system: 'System',
    explore: 'Explore',
    
    // Profile
    personalData: 'PERSONAL DATA',
    fullNameLabel: 'Full Name',
    editProfile: 'Edit Profile Information',
    confirmChanges: 'Confirm Changes',
    syncing: 'Syncing...',
    preferences: 'PREFERENCES & SECURITY',
    darkTheme: 'Dark Mode',
    changePass: 'Change Password',
    biometrics: 'Biometrics',
    language: 'Language',
    logout: 'Logout Account',
    updateSecurity: 'Update Security',
    oldPass: 'Old Password',
    newPass: 'New Password',
    confirmNew: 'Confirm New',
    update: 'Update',
    cancel: 'Cancel',
    chooseLang: 'Choose Language',
    close: 'Close',
    confirmLogout: 'Confirm Logout',
    areYouSureLogout: 'Are you sure you want to logout from your account?',
    
    // Notifications
    notifications: 'Notifications',
    markAllRead: 'Mark all as read',
    noNotifications: 'No new notifications',

    // Help
    helpCenter: 'Help Center',
    helpSubtitle: 'We are ready to help you with any questions or technical issues.',
    emergencyTitle: 'Direct Support',
    emergencySubtitle: 'Contact us for urgent assistance',
    contactSupport: 'Contact Us',
    faqTitle: 'Frequently Asked Questions (FAQ)',

    // Help Extra
    supportCenter: 'Support Center',
    searchDoc: 'Search documentation...',
    browseTopics: 'Browse Topics',
    popularFaq: 'Popular FAQs',
    whatsapp: 'WhatsApp',
    emailSupport: 'Email Support',
    web: 'Web',
    billing: 'Billing',
    // Notifications Extra
    recentNotifications: 'recent notifications',
  },
  Indonesian: {
    // Auth
    login: 'Masuk Sekarang',
    register: 'Daftar Sekarang',
    createAccount: 'Buat Akun Baru',
    registerSubtitle: 'Bergabunglah dengan kami untuk mulai mengelola ruang kerja Anda.',
    email: 'Alamat Email',
    password: 'Kata Sandi',
    fullName: 'Nama Lengkap',
    forgotPass: 'Lupa Kata Sandi?',
    rememberMe: 'Ingat Saya',
    noAccount: 'Belum punya akun? ',
    haveAccount: 'Sudah punya akun? ',
    loginJust: 'Masuk Saja',
    termsText: 'Dengan mendaftar, Anda menyetujui ',
    termsLink: 'Ketentuan Layanan',
    privacyLink: 'Kebijakan Privasi',
    and: ' dan ',

    // Auth Extra
    signIn: 'Masuk',
    emailPlaceholder: 'email@contoh.com',
    passwordPlaceholder: '••••••••',
    signInNow: 'Masuk Sekarang',
    orContinueWith: 'ATAU LANJUTKAN DENGAN',
    signUp: 'Daftar',
    google: 'Google',
    apple: 'Apple',
    welcomeBack: 'Selamat datang kembali!',
    invalidEmail: 'Alamat email tidak valid',
    loginFailed: 'Login gagal. Silakan coba lagi.',
    bioConfirm: 'Konfirmasi Identitas',
    bioFailed: 'Autentikasi biometrik gagal',
    bioSuccess: 'Login Biometrik Berhasil!',

    // Auth Extra 2
    fillAll: 'Silakan isi semua bidang yang diperlukan',
    passMismatch: 'Kata sandi tidak cocok',
    accountCreated: 'Akun berhasil dibuat!',
    confirmPassword: 'Konfirmasi Kata Sandi',
    namePlaceholder: 'John Doe',
    registering: 'Membuat akun...',

    // Profile Extra
    uploadingAvatar: 'Mengunggah foto...',
    avatarUpdated: 'Foto profil diperbarui!',
    profileUpdated: 'Profil berhasil diperbarui!',
    logoutSafe: 'Keluar dengan aman...',
    confirmLogout: 'Apakah Anda yakin ingin keluar?',
    cancel: 'Batal',
    logout: 'Keluar',
    accCreated: 'Akun berhasil dibuat!',
    regFailed: 'Pendaftaran gagal',
    join: 'Bergabunglah dengan',
    confirmPass: 'Konfirmasi Kata Sandi',
    namePlaceholder: 'Budi Santoso',

    // Dashboard
    halo: 'Halo',
    role: 'Peran Anda: ',
    lastStatus: 'Status Terakhir: ',
    history: 'Aktivitas Terbaru',
    searchPlaceholder: 'Cari item atau lokasi...',
    updateNow: 'Perbarui Sekarang',
    all: 'Semua',
    pending: 'Tertunda',
    completed: 'Selesai',
    high: 'Penting',
    searching: 'Mencari di server...',

    // Dashboard Extra
    systemSupport: 'Dukungan Sistem',
    instantHelp: 'Bantuan Instan 24/7',
    getHelp: 'Dapatkan Bantuan',
    quickActions: 'Aksi Cepat',
    categories: 'Kategori',
    latestDiscoveries: 'Penemuan Terbaru',
    account: 'Akun',
    subscription: 'Langganan',
    system: 'Sistem',
    explore: 'Jelajahi',

    // Profile
    personalData: 'DATA PRIBADI',
    fullNameLabel: 'Nama Lengkap',
    editProfile: 'Ubah Informasi Profil',
    confirmChanges: 'Simpan Perubahan',
    syncing: 'Menyinkronkan...',
    preferences: 'PREFERENSI & KEAMANAN',
    darkTheme: 'Mode Gelap',
    changePass: 'Ubah Kata Sandi',
    biometrics: 'Biometrik',
    language: 'Bahasa',
    logout: 'Keluar Akun',
    updateSecurity: 'Perbarui Keamanan',
    oldPass: 'Sandi Lama',
    newPass: 'Sandi Baru',
    confirmNew: 'Konfirmasi Sandi Baru',
    update: 'Perbarui',
    cancel: 'Batal',
    chooseLang: 'Pilih Bahasa',
    close: 'Tutup',
    confirmLogout: 'Konfirmasi Keluar',
    areYouSureLogout: 'Apakah Anda yakin ingin keluar dari akun Anda?',

    // Notifications
    notifications: 'Pemberitahuan',
    markAllRead: 'Tandai semua dibaca',
    noNotifications: 'Tidak ada pemberitahuan baru',

    // Notifications Extra
    recentNotifications: 'pemberitahuan terbaru',

    // Help
    helpCenter: 'Pusat Bantuan',
    helpSubtitle: 'Kami siap membantu Anda dengan pertanyaan atau kendala teknis.',
    emergencyTitle: 'Dukungan Langsung',
    emergencySubtitle: 'Hubungi kami untuk bantuan mendesak',
    contactSupport: 'Hubungi Kami',
    faqTitle: 'Pertanyaan Umum (FAQ)',

    // Help Extra
    supportCenter: 'Pusat Dukungan',
    searchDoc: 'Cari dokumentasi...',
    browseTopics: 'Telusuri Topik',
    popularFaq: 'FAQ Populer',
    whatsapp: 'WhatsApp',
    emailSupport: 'Dukungan Email',
    web: 'Web',
    billing: 'Tagihan',
  }
};

interface LanguageContextType {
  language: LanguageType;
  setLanguage: (lang: LanguageType) => void;
  t: any;
}

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

export function LanguageProvider({ children }: { children: React.ReactNode }) {
  const [language, setRawLanguage] = useState<LanguageType>('English');
  const { config } = useAppConfig();

  useEffect(() => {
    loadLanguage();
  }, []);

  const loadLanguage = async () => {
    const saved = await storage.get('pref_language');
    if (saved === 'English' || saved === 'Indonesian') {
      setRawLanguage(saved);
    }
  };

  const setLanguage = async (newLang: LanguageType) => {
    setRawLanguage(newLang);
    await storage.save('pref_language', newLang);
  };

  // Merge static translations with dynamic ones from Laravel
  const t = {
    ...translations[language],
    ...(config?.localization?.[language] || {})
  };

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

export function useTranslation() {
  const context = useContext(LanguageContext);
  if (context === undefined) {
    return {
      language: 'English',
      setLanguage: () => {},
      t: translations.English
    };
  }
  return context;
}
