'use client';

import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { apiFetch } from '@/lib/api';

interface PublicSettingsContextValue {
  projectName: string;
  projectTagline: string;
  ldapEnabled: boolean;
  ldapUseLdaps: boolean;
  isLoading: boolean;
  refreshPublicSettings: () => Promise<void>;
}

const PublicSettingsContext = createContext<PublicSettingsContextValue>({
  projectName: 'MVK ID',
  projectTagline: 'Единый аккаунт для сервисов Lendry',
  ldapEnabled: false,
  ldapUseLdaps: false,
  isLoading: true,
  refreshPublicSettings: async () => undefined
});

export function PublicSettingsProvider({ children }: { children: React.ReactNode }) {
  const [settings, setSettings] = useState<Record<string, string>>({});
  const [isLoading, setIsLoading] = useState(true);

  const refreshPublicSettings = useCallback(async () => {
    try {
      const response = await apiFetch<{ settings: Array<{ key: string; value: string }> }>('/settings/public');
      const map = Object.fromEntries((response.settings ?? []).map((item) => [item.key, item.value]));
      setSettings(map);
    } catch {
      // Оставляем последние известные значения.
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    void refreshPublicSettings();
    const onFocus = () => void refreshPublicSettings();
    window.addEventListener('focus', onFocus);
    return () => window.removeEventListener('focus', onFocus);
  }, [refreshPublicSettings]);

  const value = useMemo(
    () => ({
      projectName: settings.PROJECT_NAME || 'MVK ID',
      projectTagline: settings.PROJECT_TAGLINE || 'Единый аккаунт для сервисов Lendry',
      ldapEnabled: ['true', '1', 'yes'].includes((settings.LDAP_ENABLED ?? '').trim().toLowerCase()),
      ldapUseLdaps: ['true', '1', 'yes'].includes((settings.LDAP_USE_LDAPS ?? '').trim().toLowerCase()),
      isLoading,
      refreshPublicSettings
    }),
    [isLoading, refreshPublicSettings, settings.LDAP_ENABLED, settings.LDAP_USE_LDAPS, settings.PROJECT_NAME, settings.PROJECT_TAGLINE]
  );

  return <PublicSettingsContext.Provider value={value}>{children}</PublicSettingsContext.Provider>;
}

export function usePublicSettings() {
  return useContext(PublicSettingsContext);
}
