'use client';

import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { apiFetch } from '@/lib/api';
import { DEFAULT_PUBLIC_API_URL, DEFAULT_PUBLIC_FRONTEND_URL, inferApiBaseFromProjectDomain } from '@/lib/project-domains';
import { FirebasePublicConfig, parseFirebasePublicConfig } from '@/lib/firebase-config';

interface PublicSettingsContextValue {
  projectName: string;
  projectTagline: string;
  publicApiUrl: string;
  publicFrontendUrl: string;
  ldapEnabled: boolean;
  ldapUseLdaps: boolean;
  pinLockTimeoutMinutes: number;
  firebaseConfig: FirebasePublicConfig | null;
  isLoading: boolean;
  refreshPublicSettings: () => Promise<void>;
}

const PublicSettingsContext = createContext<PublicSettingsContextValue>({
  projectName: 'MVK ID',
  projectTagline: 'Единый аккаунт для сервисов Lendry',
  publicApiUrl: DEFAULT_PUBLIC_API_URL,
  publicFrontendUrl: DEFAULT_PUBLIC_FRONTEND_URL,
  ldapEnabled: false,
  ldapUseLdaps: false,
  pinLockTimeoutMinutes: 15,
  firebaseConfig: null,
  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();
  }, [refreshPublicSettings]);

  const value = useMemo(() => {
    const projectDomain = settings.PROJECT_DOMAIN?.trim();
    const inferredApi = projectDomain ? inferApiBaseFromProjectDomain(projectDomain) : null;
    const publicApiUrl = settings.PUBLIC_API_URL?.trim() || inferredApi || DEFAULT_PUBLIC_API_URL;
    const publicFrontendUrl =
      settings.PUBLIC_FRONTEND_URL?.trim() ||
      (projectDomain
        ? projectDomain.startsWith('http')
          ? projectDomain.replace(/\/+$/, '')
          : `https://${projectDomain.replace(/^\/+/, '')}`
        : DEFAULT_PUBLIC_FRONTEND_URL);

    return {
      projectName: settings.PROJECT_NAME || 'MVK ID',
      projectTagline: settings.PROJECT_TAGLINE || 'Единый аккаунт для сервисов Lendry',
      publicApiUrl: publicApiUrl.replace(/\/+$/, ''),
      publicFrontendUrl: publicFrontendUrl.replace(/\/+$/, ''),
      ldapEnabled: ['true', '1', 'yes'].includes((settings.LDAP_ENABLED ?? '').trim().toLowerCase()),
      ldapUseLdaps: ['true', '1', 'yes'].includes((settings.LDAP_USE_LDAPS ?? '').trim().toLowerCase()),
      pinLockTimeoutMinutes: Math.max(1, Number.parseInt(settings.PIN_LOCK_TIMEOUT_MINUTES ?? '15', 10) || 15),
      firebaseConfig: parseFirebasePublicConfig(settings),
      isLoading,
      refreshPublicSettings
    };
  }, [isLoading, refreshPublicSettings, settings]);

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

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