"use client";

import { create } from "zustand";
import { persist } from "zustand/middleware";

// ── Feature flags ─────────────────────────────────────────────────────────────

export type FeatureFlags = {
  enableModules: boolean;
  enableWorkspaceSettings: boolean;
  enableAuthConfig: boolean;
  enableClientStatistics: boolean;
  enableSdkDocs: boolean;
  enableClusterHealth: boolean;
  compactDatagrid: boolean;
  showRowNumbers: boolean;
  showColumnIcons: boolean;
  showDocumentIcons: boolean;
  sortColumnsByDdl: boolean;
  hideNullColumns: boolean;
};

const DEFAULT_FLAGS: FeatureFlags = {
  enableModules: true,
  enableWorkspaceSettings: true,
  enableAuthConfig: true,
  enableClientStatistics: true,
  enableSdkDocs: true,
  enableClusterHealth: true,
  compactDatagrid: false,
  showRowNumbers: true,
  showColumnIcons: true,
  showDocumentIcons: true,
  sortColumnsByDdl: true,
  hideNullColumns: false,
};

// ── Workspace settings ────────────────────────────────────────────────────────

export type WorkspaceSettings = {
  name: string;
  slug: string;
  logoUrl: string;
  logoInitials: string;
  logoColor: string;
  region: string;
  fiscalYearStart: string;
};

const DEFAULT_WORKSPACE: WorkspaceSettings = {
  name: "My Workspace",
  slug: "my-workspace",
  logoUrl: "",
  logoInitials: "MW",
  logoColor: "#6366f1",
  region: "United States",
  fiscalYearStart: "January",
};

// ── Preferences ───────────────────────────────────────────────────────────────

export type Preferences = {
  sidebarMinWidth: number;
  sidebarMaxWidth: number;
  inspectorMinWidth: number;
  inspectorMaxWidth: number;
  sidebarOpen: boolean;
  inspectorOpen: boolean;
  autoFitColumnWidth: boolean;
  maxAutoColumnWidth: number;
};

const DEFAULT_PREFERENCES: Preferences = {
  sidebarMinWidth: 10,
  sidebarMaxWidth: 30,
  inspectorMinWidth: 12,
  inspectorMaxWidth: 40,
  sidebarOpen: true,
  inspectorOpen: true,
  autoFitColumnWidth: true,
  maxAutoColumnWidth: 400,
};

// ── Auth config ───────────────────────────────────────────────────────────────

export type AuthFieldMapping = {
  id: string;
  email: string;
  displayName: string;
  avatarUrl: string;
  role: string;
  createdAt: string;
  lastSignIn: string;
};

export type AuthConfig = {
  usersTable: string;
  usersSchema: string;
  fieldMapping: AuthFieldMapping;
  authProvider: "supabase" | "better-auth" | "custom";
};

const DEFAULT_AUTH_CONFIG: AuthConfig = {
  usersTable: "",
  usersSchema: "public",
  fieldMapping: {
    id: "id",
    email: "email",
    displayName: "display_name",
    avatarUrl: "avatar_url",
    role: "role",
    createdAt: "created_at",
    lastSignIn: "last_sign_in_at",
  },
  authProvider: "supabase",
};

// ── Modules (micro-frontends / extensions) ────────────────────────────────────

export type DbEngine = "postgres" | "supabase" | "scylladb" | "mysql" | "other";

export type Module = {
  id: string;
  name: string;
  description: string;
  type: "client" | "extension" | "integration";
  dbEngine?: DbEngine;
  status: "active" | "inactive" | "pending";
  createdAt: string;
  /** @deprecated for non-Postgres engines use connectionUrl instead */
  pgUrl?: string;
  connectionUrl?: string;
  supabaseUrl?: string;
  supabaseKey?: string;
  scyllaHosts?: string;
  scyllaKeyspace?: string;
  scyllaUsername?: string;
  scyllaPassword?: string;
};

// ── Store ─────────────────────────────────────────────────────────────────────

type AppStore = {
  flags: FeatureFlags;
  workspace: WorkspaceSettings;
  preferences: Preferences;
  authConfig: AuthConfig;
  modules: Module[];
  selectedClient: string | null;

  setFlag: (key: keyof FeatureFlags, value: boolean) => void;
  setFlags: (flags: Partial<FeatureFlags>) => void;
  setWorkspace: (settings: Partial<WorkspaceSettings>) => void;
  setPreferences: (prefs: Partial<Preferences>) => void;
  setAuthConfig: (config: Partial<AuthConfig>) => void;
  setAuthFieldMapping: (mapping: Partial<AuthFieldMapping>) => void;
  addModule: (module: Module) => void;
  removeModule: (id: string) => void;
  updateModule: (id: string, update: Partial<Module>) => void;
  setSelectedClient: (client: string | null) => void;
};

export const useAppStore = create<AppStore>()(
  persist(
    (set) => ({
      flags: DEFAULT_FLAGS,
      workspace: DEFAULT_WORKSPACE,
      preferences: DEFAULT_PREFERENCES,
      authConfig: DEFAULT_AUTH_CONFIG,
      modules: [],
      selectedClient: null,

      setFlag: (key, value) =>
        set((s) => ({ flags: { ...s.flags, [key]: value } })),

      setFlags: (flags) =>
        set((s) => ({ flags: { ...s.flags, ...flags } })),

      setWorkspace: (settings) =>
        set((s) => ({ workspace: { ...s.workspace, ...settings } })),

      setPreferences: (prefs) =>
        set((s) => ({ preferences: { ...s.preferences, ...prefs } })),

      setAuthConfig: (config) =>
        set((s) => ({ authConfig: { ...s.authConfig, ...config } })),

      setAuthFieldMapping: (mapping) =>
        set((s) => ({
          authConfig: {
            ...s.authConfig,
            fieldMapping: { ...s.authConfig.fieldMapping, ...mapping },
          },
        })),

      addModule: (module) =>
        set((s) => ({ modules: [...s.modules, module] })),

      removeModule: (id) =>
        set((s) => ({ modules: s.modules.filter((m) => m.id !== id) })),

      updateModule: (id, update) =>
        set((s) => ({
          modules: s.modules.map((m) => (m.id === id ? { ...m, ...update } : m)),
        })),

      setSelectedClient: (client) => set({ selectedClient: client }),
    }),
    {
      name: "athena-app-store",
      version: 3,
      migrate: (persisted, version) => {
        const state = persisted as Record<string, unknown>;
        if (version < 2) {
          state.preferences = DEFAULT_PREFERENCES;
          state.selectedClient = null;
        }
        if (version < 3) {
          const prefs = state.preferences as Record<string, unknown> | undefined;
          if (prefs) {
            prefs.sidebarOpen = prefs.sidebarOpen ?? true;
            prefs.inspectorOpen = prefs.inspectorOpen ?? true;
          }
        }
        return state as AppStore;
      },
    },
  ),
);
