import {
  createContext,
  useContext,
  useState,
  useCallback,
  type ReactNode,
} from 'react';
import { Navigate } from 'react-router-dom';

// ============================================================
//  Types
// ============================================================

export type CrmModuleKey = 'contacts' | 'companies' | 'deals' | 'pipelines' | 'lexware';

export interface CrmModuleConfig {
  enabled: boolean;
  label?: string; // Für spätere Umbenennung
}

export interface CrmSettings {
  modules: Record<CrmModuleKey, CrmModuleConfig>;
}

interface CrmSettingsContextValue {
  settings: CrmSettings;
  updateSettings: (next: CrmSettings) => void;
  toggleModule: (key: CrmModuleKey, enabled: boolean) => void;
  isModuleEnabled: (key: CrmModuleKey) => boolean;
}

// ============================================================
//  Defaults & localStorage
// ============================================================

const STORAGE_KEY = 'crm-settings';

const DEFAULT_SETTINGS: CrmSettings = {
  modules: {
    contacts: { enabled: true },
    companies: { enabled: true },
    deals: { enabled: true },
    pipelines: { enabled: true },
    lexware: { enabled: true },
  },
};

function loadSettings(): CrmSettings {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return DEFAULT_SETTINGS;
    const parsed = JSON.parse(raw) as Partial<CrmSettings>;
    // Merge mit Defaults (falls neue Module hinzukommen)
    return {
      modules: {
        ...DEFAULT_SETTINGS.modules,
        ...(parsed.modules ?? {}),
      },
    };
  } catch {
    return DEFAULT_SETTINGS;
  }
}

function saveSettings(settings: CrmSettings): void {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
  } catch {
    // localStorage voll oder nicht verfügbar — ignorieren
  }
}

// ============================================================
//  Context + Provider
// ============================================================

const CrmSettingsCtx = createContext<CrmSettingsContextValue | null>(null);

export function CrmSettingsProvider({ children }: { children: ReactNode }) {
  const [settings, setSettings] = useState<CrmSettings>(loadSettings);

  const updateSettings = useCallback((next: CrmSettings) => {
    setSettings(next);
    saveSettings(next);
  }, []);

  const toggleModule = useCallback(
    (key: CrmModuleKey, enabled: boolean) => {
      setSettings((prev) => {
        const next: CrmSettings = {
          ...prev,
          modules: {
            ...prev.modules,
            [key]: { ...prev.modules[key], enabled },
          },
        };
        saveSettings(next);
        return next;
      });
    },
    [],
  );

  const isModuleEnabled = useCallback(
    (key: CrmModuleKey) => settings.modules[key]?.enabled ?? true,
    [settings],
  );

  return (
    <CrmSettingsCtx.Provider
      value={{ settings, updateSettings, toggleModule, isModuleEnabled }}
    >
      {children}
    </CrmSettingsCtx.Provider>
  );
}

// ============================================================
//  Hook
// ============================================================

export function useCrmSettings(): CrmSettingsContextValue {
  const ctx = useContext(CrmSettingsCtx);
  if (!ctx) {
    throw new Error('useCrmSettings must be used within CrmSettingsProvider');
  }
  return ctx;
}

// ============================================================
//  Route Guard
// ============================================================

/**
 * Wraps a CRM page — redirects to "/" if the module is disabled.
 */
export function CrmModuleGuard({
  module: mod,
  children,
}: {
  module: CrmModuleKey;
  children: ReactNode;
}) {
  const { isModuleEnabled } = useCrmSettings();
  if (!isModuleEnabled(mod)) return <Navigate to="/" replace />;
  return <>{children}</>;
}
