"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import {
  Alert,
  Button,
  Card,
  Col,
  Descriptions,
  Divider,
  Drawer,
  Empty,
  Form,
  Input,
  InputNumber,
  List,
  Modal,
  Popconfirm,
  Row,
  Select,
  Space,
  Switch,
  Tabs,
  Tag,
  Table,
  Typography,
  message,
} from "antd";
import type { TabsProps } from "antd";
import type { ColumnsType } from "antd/es/table";
import { DeleteOutlined, EyeInvisibleOutlined, EyeOutlined, HistoryOutlined, PlusOutlined, ReloadOutlined, WarningOutlined } from "@ant-design/icons";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";

import {
  deriveOrgSyncFreshness,
  fetchDepartments,
  fetchEmployeesByDepartment,
  fetchOrgSyncRuns,
  fetchOrgSyncRuntimeStatus,
  searchEmployees,
  syncDepartments,
  type OrgSyncFreshnessSummary,
  type Department,
  type Employee,
  type OrgSyncRun,
  type OrgSyncRuntimeStatus,
} from "@/lib/api/department";
import { usePlatformBranding } from "@/lib/branding/platform-branding";
import {
  createAlertRule,
  deleteAlertRule,
  describeAlertRoutingBoundary,
  fetchAlertDeliveries,
  fetchAlertFields,
  fetchAlertRules,
  fetchAlertRuns,
  fetchAlertRuntimeStatus,
  refreshAlertRuntime,
  startAlertRuntime,
  stopAlertRuntime,
  renderAlertCardTemplate,
  runAlertRuleNow,
  testAlertSend,
  updateAlertRule,
  type AlertRoutingBoundarySummary,
} from "@/lib/api/alerts";
import { useSystemSettings } from "@/lib/hooks/use-system-settings";
import { useAuthStore } from "@/store/auth-store";
import type { AlertFieldInfo, AlertRuntimeStatus, LarkAlertDelivery, LarkAlertRule, LarkAlertRun } from "@/types/alerts";
import type {
  AuthenticationSettings,
  DataSyncSettings,
  NotificationSettings,
  PlatformSettings,
  SystemHealth,
  SystemSettings,
  SystemVersion,
} from "@/types/settings";

const { Title, Paragraph, Text } = Typography;

type SectionKey = "platform" | "authentication" | "notifications" | "org_sync";
type SectionPayloadMap = {
  platform: PlatformSettings;
  authentication: AuthenticationSettings;
  notifications: NotificationSettings;
  data_sync: DataSyncSettings;
};

type PlatformFormValues = PlatformSettings & { changeNote?: string };
type AuthFormValues = AuthenticationSettings & { changeNote?: string };
type NotificationFormValues = NotificationSettings & { changeNote?: string };
type OrgSyncFormValues = Pick<
  DataSyncSettings,
  | "org_sync_enabled"
  | "org_provider"
  | "org_sync_cron"
  | "org_sync_stale_after_hours"
  | "org_sync_expired_after_hours"
  | "lark_app_id"
  | "lark_app_secret"
> & { changeNote?: string };

type AlertConditionFormValue = {
  field?: string;
  op?: string;
  value?: string;
};

type AlertRuleFormValues = {
  id?: number;
  name: string;
  enabled: boolean;
  entity_type: string;
  cron_expr?: string;
  event_on_create: boolean;
  event_on_update: boolean;
  event_on_status_change: boolean;
  event_on_severity_change: boolean;
  send_via_webhook: boolean;
  send_via_app: boolean;
  recipient_employee_ids?: number[];
  recipient_target_keys?: ("security_team" | "rd_team" | "entity_department" | "entity_owner" | "entity_fixer" | "entity_submitter")[];
  max_matches_per_run: number;
  card_template: string;
  conditions: AlertConditionFormValue[];
  preview_entity_id?: number;
};

type TestSendFormValues = {
  employee_id?: number;
  send_webhook: boolean;
  card_template: string;
  preview_entity_type?: string;
  preview_entity_id?: number;
};

const initialSavingState: Record<SectionKey, boolean> = {
  platform: false,
  authentication: false,
  notifications: false,
  org_sync: false,
};

const severityOptions = ["low", "medium", "high", "critical"];

const DEFAULT_SLA_REMINDER_SETTINGS: Pick<
  NotificationSettings,
  "vulnerability_sla_reminders_enabled" | "vulnerability_sla_due_soon_before_hours" | "vulnerability_sla_overdue_repeat_hours"
> = {
  vulnerability_sla_reminders_enabled: false,
  vulnerability_sla_due_soon_before_hours: 24,
  vulnerability_sla_overdue_repeat_hours: 24,
};

const normalizeNotificationSettings = (settings: NotificationSettings): NotificationSettings => ({
  ...DEFAULT_SLA_REMINDER_SETTINGS,
  ...settings,
});

const isPositiveInteger = (value: unknown): value is number =>
  typeof value === "number" && Number.isInteger(value) && value > 0;

const PLATFORM_COMPARABLE_FIELDS = [
  "display_name",
  "support_email",
  "default_timezone",
  "logo_url",
  "maintenance_mode",
] as const;

const AUTH_COMPARABLE_FIELDS = [
  "sso_provider",
  "auth0_domain",
  "auth0_client_id",
  "auth0_client_secret",
  "auth0_audience",
  "enforce_sso",
  "default_role",
  "session_timeout_minutes",
  "allow_local_users",
  "mfa_required",
] as const;

const NOTIFICATION_COMPARABLE_FIELDS = [
  "email_alerts",
  "email_from_address",
  "lark_alerts",
  "lark_webhook",
  "lark_app_id",
  "lark_app_secret",
  "lark_receive_id_type",
  "incident_webhook",
  "severity_threshold",
  "digest_enabled",
  "vulnerability_sla_reminders_enabled",
  "vulnerability_sla_due_soon_before_hours",
  "vulnerability_sla_overdue_repeat_hours",
] as const;

export default function SystemSettingsPage() {
  const [platformForm] = Form.useForm<PlatformFormValues>();
  const [authForm] = Form.useForm<AuthFormValues>();
  const [notificationForm] = Form.useForm<NotificationFormValues>();
  const [orgSyncForm] = Form.useForm<OrgSyncFormValues>();
  const [alertRuleForm] = Form.useForm<AlertRuleFormValues>();
  const [testSendForm] = Form.useForm<TestSendFormValues>();

  const [saving, setSaving] = useState<Record<SectionKey, boolean>>(initialSavingState);
  const [savedAt, setSavedAt] = useState<Record<SectionKey, string | null>>({
    platform: null,
    authentication: null,
    notifications: null,
    org_sync: null,
  });
  const [hasConflict, setHasConflict] = useState(false);
  const [orgSyncLoading, setOrgSyncLoading] = useState(false);
  const [orgSyncingNow, setOrgSyncingNow] = useState(false);
  const [orgRuntimeStatus, setOrgRuntimeStatus] = useState<OrgSyncRuntimeStatus | null>(null);
  const [orgSyncRuns, setOrgSyncRuns] = useState<OrgSyncRun[]>([]);
  const [orgDepartments, setOrgDepartments] = useState<Department[]>([]);
  const [deptEmployees, setDeptEmployees] = useState<Record<string, Employee[]>>({});
  const [deptEmployeesLoading, setDeptEmployeesLoading] = useState<string | null>(null);
  const [employeeSearchLoading, setEmployeeSearchLoading] = useState(false);
  const [employeeSearchResults, setEmployeeSearchResults] = useState<Employee[]>([]);

  const [alertLoading, setAlertLoading] = useState(false);
  const [alertRuntimeStatus, setAlertRuntimeStatus] = useState<AlertRuntimeStatus | null>(null);
  const [alertRules, setAlertRules] = useState<LarkAlertRule[]>([]);
  const [alertRuns, setAlertRuns] = useState<LarkAlertRun[]>([]);
  const [alertRuleModalOpen, setAlertRuleModalOpen] = useState(false);
  const [alertEditingRule, setAlertEditingRule] = useState<LarkAlertRule | null>(null);
  const [alertFields, setAlertFields] = useState<AlertFieldInfo[]>([]);
  const [alertFieldsLoading, setAlertFieldsLoading] = useState(false);
  const [alertRecipientSearchLoading, setAlertRecipientSearchLoading] = useState(false);
  const [alertRecipientOptions, setAlertRecipientOptions] = useState<Employee[]>([]);
  const [deliveriesDrawerOpen, setDeliveriesDrawerOpen] = useState(false);
  const [selectedRun, setSelectedRun] = useState<LarkAlertRun | null>(null);
  const [runDeliveries, setRunDeliveries] = useState<LarkAlertDelivery[]>([]);
  const [runDeliveriesLoading, setRunDeliveriesLoading] = useState(false);
  const [templatePreview, setTemplatePreview] = useState<unknown>(null);
  const [templatePreviewOpen, setTemplatePreviewOpen] = useState(false);
  const [testSendModalOpen, setTestSendModalOpen] = useState(false);
  const [sensitiveConfigured, setSensitiveConfigured] = useState(() => ({
    auth0_client_secret: false,
    lark_webhook: false,
    lark_alert_app_secret: false,
    incident_webhook: false,
    org_lark_app_secret: false,
  }));

  const searchParams = useSearchParams();
  const pathname = usePathname();
  const router = useRouter();

  const [activeTab, setActiveTab] = useState(() => searchParams?.get("tab") ?? "platform");

  useEffect(() => {
    const tab = searchParams?.get("tab");
    if (tab && tab !== activeTab) {
      setActiveTab(tab);
    }
  }, [searchParams, activeTab]);

  const handleTabChange = useCallback(
    (key: string) => {
      setActiveTab(key);
      const next = new URLSearchParams(searchParams?.toString());
      next.set("tab", key);
      router.replace(`${pathname}?${next.toString()}`, { scroll: false });
    },
    [pathname, router, searchParams],
  );

  const canEdit = useAuthStore((state) => state.hasPermission("system:manage_settings"));

  const { config: settings, health, loading, error, refresh, save, versionInfo } = useSystemSettings();
  const { setBranding } = usePlatformBranding();

  useEffect(() => {
    refresh().catch((err) => {
      const msg = extractErrorMessage(err) ?? "Failed to load settings";
      message.error(msg);
    });
  }, [refresh]);

  useEffect(() => {
    if (!settings) {
      return;
    }
    const notifications = normalizeNotificationSettings(settings.notifications);
    platformForm.setFieldsValue({ ...settings.platform, changeNote: "" });
    setSensitiveConfigured({
      auth0_client_secret: Boolean(settings.authentication.auth0_client_secret_configured),
      lark_webhook: Boolean(notifications.lark_webhook_configured),
      lark_alert_app_secret: Boolean(notifications.lark_app_secret_configured),
      incident_webhook: Boolean(notifications.incident_webhook_configured),
      org_lark_app_secret: Boolean(settings.data_sync.lark_app_secret_configured),
    });
    authForm.setFieldsValue({ ...settings.authentication, auth0_client_secret: "", changeNote: "" });
    notificationForm.setFieldsValue({
      ...notifications,
      lark_webhook: "",
      lark_app_secret: "",
      incident_webhook: "",
      changeNote: "",
    });
    orgSyncForm.setFieldsValue({
      org_sync_enabled: settings.data_sync.org_sync_enabled,
      org_provider: settings.data_sync.org_provider,
      org_sync_cron: settings.data_sync.org_sync_cron,
      org_sync_stale_after_hours: settings.data_sync.org_sync_stale_after_hours,
      org_sync_expired_after_hours: settings.data_sync.org_sync_expired_after_hours,
      lark_app_id: settings.data_sync.lark_app_id,
      lark_app_secret: "",
      changeNote: "",
    });
  }, [settings, platformForm, authForm, notificationForm, orgSyncForm]);

  const platformWatcher = Form.useWatch([], platformForm);
  const authWatcher = Form.useWatch([], authForm);
  const notificationWatcher = Form.useWatch([], notificationForm);
  const orgSyncWatcher = Form.useWatch([], orgSyncForm);
  const orgSyncEnabled = Form.useWatch("org_sync_enabled", orgSyncForm);
  const ssoProvider = Form.useWatch("sso_provider", authForm);

  // Revalidate lark_app_secret field when org_sync_enabled changes
  useEffect(() => {
    if (orgSyncEnabled !== undefined) {
      orgSyncForm.validateFields(['lark_app_secret']).catch(() => {
        // Ignore validation errors, just trigger revalidation
      });
    }
  }, [orgSyncEnabled, orgSyncForm]);

  const activeSSOProvider = useMemo(
    () => ((ssoProvider ?? settings?.authentication.sso_provider ?? "google") as string).toLowerCase(),
    [settings?.authentication.sso_provider, ssoProvider],
  );
  const isAuth0 = activeSSOProvider === "auth0";

  const platformBaseline = useMemo(
    () => pickComparableFields(settings?.platform, PLATFORM_COMPARABLE_FIELDS),
    [settings?.platform],
  );
  const authBaseline = useMemo(
    () =>
      sanitizeSensitiveSettings(
        pickComparableFields(settings?.authentication, AUTH_COMPARABLE_FIELDS),
        ["auth0_client_secret"],
      ),
    [settings?.authentication],
  );
  const notificationBaseline = useMemo(
    () =>
      sanitizeSensitiveSettings(
        pickComparableFields(
          settings ? normalizeNotificationSettings(settings.notifications) : undefined,
          NOTIFICATION_COMPARABLE_FIELDS,
        ),
        ["lark_webhook", "lark_app_secret", "incident_webhook"],
      ),
    [settings],
  );

  const platformChanges = useMemo(
    () => computeDiff(platformBaseline, platformWatcher, ["changeNote"]),
    [platformBaseline, platformWatcher],
  );
  const authChanges = useMemo(
    () => computeDiff(authBaseline, authWatcher, ["changeNote"]),
    [authBaseline, authWatcher],
  );
  const notificationChanges = useMemo(
    () => computeDiff(notificationBaseline, notificationWatcher, ["changeNote"]),
    [notificationBaseline, notificationWatcher],
  );
  const orgSyncBaseline = useMemo(() => {
    if (!settings) return undefined;
    return {
      org_sync_enabled: settings.data_sync.org_sync_enabled,
      org_provider: settings.data_sync.org_provider,
      org_sync_cron: settings.data_sync.org_sync_cron,
      org_sync_stale_after_hours: settings.data_sync.org_sync_stale_after_hours,
      org_sync_expired_after_hours: settings.data_sync.org_sync_expired_after_hours,
      lark_app_id: settings.data_sync.lark_app_id,
      lark_app_secret: "",
    };
  }, [settings]);
  const orgSyncChanges = useMemo(
    () => computeDiff(orgSyncBaseline, orgSyncWatcher, ["changeNote"]),
    [orgSyncBaseline, orgSyncWatcher],
  );

  const displayNameValue = platformWatcher?.display_name?.trim() ?? "";

  const platformDirty = platformChanges.length > 0;
  const authDirty = authChanges.length > 0;
  const notificationDirty = notificationChanges.length > 0;
  const orgSyncDirty = orgSyncChanges.length > 0;

  const handleRefresh = async () => {
    try {
      await refresh();
      setHasConflict(false);
      message.success("Settings reloaded");
    } catch (err) {
      message.error(extractErrorMessage(err) ?? "Failed to refresh settings");
    }
  };

  const submitSection = async (
    section: SectionKey,
    values: Partial<SectionPayloadMap["data_sync"]> | SectionPayloadMap[keyof SectionPayloadMap],
    note?: string,
  ) => {
    const currentSettings = settings;
    if (!currentSettings) return false;
    setSaving((prev) => ({ ...prev, [section]: true }));
    try {
      const payload = {
        platform: currentSettings.platform,
        authentication: currentSettings.authentication,
        notifications: normalizeNotificationSettings(currentSettings.notifications),
        data_sync: currentSettings.data_sync,
        version: currentSettings.version,
        note,
      };

      switch (section) {
        case "platform":
          payload.platform = values as PlatformSettings;
          break;
        case "authentication":
          payload.authentication = values as AuthenticationSettings;
          break;
        case "notifications":
          payload.notifications = values as NotificationSettings;
          break;
        case "org_sync":
          payload.data_sync = {
            ...currentSettings.data_sync,
            ...(values as Partial<DataSyncSettings>),
          };
          break;
        default:
          break;
      }

      await save(payload);
      setHasConflict(false);
      setSavedAt((prev) => ({ ...prev, [section]: new Date().toISOString() }));
      message.success("Settings updated");
      return true;
    } catch (err) {
      const status = (err as { response?: { status?: number } })?.response?.status;
      const messageText = extractErrorMessage(err) ?? "Failed to update settings";
      if (status === 409 || status === 412 || messageText.toLowerCase().includes("version")) {
        setHasConflict(true);
      }
      message.error(messageText);
      return false;
    } finally {
      setSaving((prev) => ({ ...prev, [section]: false }));
    }
  };

  const handlePlatformSave = async (values: PlatformFormValues) => {
    const { changeNote, ...payload } = values;
    const success = await submitSection("platform", payload, changeNote);
    if (success) {
      platformForm.setFieldsValue({ ...payload, changeNote: "" });
      setBranding(payload);
    }
  };

  const handleNotificationSave = async (values: NotificationFormValues) => {
    const { changeNote, ...payload } = values;
    const normalizedPayload = normalizeNotificationSettings(payload);
    if (
      !isPositiveInteger(normalizedPayload.vulnerability_sla_due_soon_before_hours) ||
      !isPositiveInteger(normalizedPayload.vulnerability_sla_overdue_repeat_hours)
    ) {
      message.error("SLA reminder hours must be positive integers");
      return;
    }

    const success = await submitSection("notifications", normalizedPayload, changeNote);
    if (success) {
      notificationForm.setFieldsValue({ ...normalizedPayload, changeNote: "" });
      if (activeTab === "alert" && canEdit) {
        void refreshAlertsData();
      }
    }
  };

  const handleAuthSave = async (values: AuthFormValues) => {
    const { changeNote, ...payload } = values;
    const success = await submitSection(
      "authentication",
      {
        ...payload,
        allow_local_users: settings?.authentication.allow_local_users ?? false,
      },
      changeNote,
    );
    if (success) {
      authForm.setFieldsValue({ ...payload, changeNote: "" });
    }
  };

  const handleOrgSyncSave = async (values: OrgSyncFormValues) => {
    const { changeNote, ...payload } = values;

    // Validate that if org sync is enabled, we have the required credentials
    if (payload.org_sync_enabled) {
      const hasAppId = Boolean(payload.lark_app_id?.trim());
      const hasAppSecret = Boolean(payload.lark_app_secret?.trim()) || sensitiveConfigured.org_lark_app_secret;

      if (!hasAppId || !hasAppSecret) {
        message.error("Lark App ID and App Secret are required when org sync is enabled");
        return;
      }
    }

    const success = await submitSection("org_sync", payload, changeNote);
    if (success) {
      orgSyncForm.setFieldsValue({ ...payload, lark_app_secret: "", changeNote: "" });
      // Update configured state after successful save
      if (payload.lark_app_secret?.trim()) {
        setSensitiveConfigured(prev => ({ ...prev, org_lark_app_secret: true }));
      }
      const runtime = await fetchOrgSyncRuntimeStatus();
      setOrgRuntimeStatus(runtime);
      const hasSavedCredentials = Boolean(payload.lark_app_id?.trim() && (payload.lark_app_secret?.trim() || sensitiveConfigured.org_lark_app_secret));
      if (payload.org_sync_enabled && hasSavedCredentials) {
        if (runtime.last_error) {
          message.warning(`Org Sync settings saved, but runtime reports: ${runtime.last_error}`);
        } else if (!runtime.scheduler_running) {
          message.warning("Org Sync settings saved, but the scheduler is stopped. Start or reconfigure the runtime before relying on scheduled sync.");
        }
      }
      if (activeTab === "org_sync" && canEdit) {
        void refreshOrgSyncData();
      }
    }
  };

  const refreshOrgSyncData = useCallback(async () => {
    if (!canEdit) return;
    setOrgSyncLoading(true);
    try {
      const [runtime, runs] = await Promise.all([
        fetchOrgSyncRuntimeStatus(),
        fetchOrgSyncRuns(),
      ]);
      setOrgRuntimeStatus(runtime);
      setOrgSyncRuns(runs ?? []);

      try {
        const depts = await fetchDepartments();
        setOrgDepartments(depts ?? []);
        setDeptEmployees({});
        setDeptEmployeesLoading(null);
      } catch (err) {
        if (isOrgSyncPickerReadsBlockedError(err)) {
          setOrgDepartments([]);
          setDeptEmployees({});
          setDeptEmployeesLoading(null);
          return;
        }
        throw err;
      }
    } catch (err) {
      message.error(extractErrorMessage(err) ?? "Failed to load org sync data");
    } finally {
      setOrgSyncLoading(false);
    }
  }, [canEdit]);

  const refreshAlertsData = useCallback(async () => {
    if (!canEdit) return;
    setAlertLoading(true);
    try {
      const [runtime, rules, runs] = await Promise.all([
        fetchAlertRuntimeStatus(),
        fetchAlertRules(),
        fetchAlertRuns(),
      ]);
      setAlertRuntimeStatus(runtime);
      setAlertRules(rules ?? []);
      setAlertRuns(runs ?? []);
    } catch (err) {
      message.error(extractErrorMessage(err) ?? "Failed to load Lark alert data");
    } finally {
      setAlertLoading(false);
    }
  }, [canEdit]);

  const handleRefreshAlertRuntime = async () => {
    if (!canEdit) return;
    try {
      const status = await refreshAlertRuntime();
      setAlertRuntimeStatus(status);
      message.success("Alert runtime refreshed");
      await refreshAlertsData();
    } catch (err) {
      message.error(extractErrorMessage(err) ?? "Failed to refresh alert runtime");
    }
  };

  const handleStartAlertRuntime = async () => {
    if (!canEdit) return;
    try {
      const status = await startAlertRuntime();
      setAlertRuntimeStatus(status);
      message.success("Alert runtime started");
      await refreshAlertsData();
    } catch (err) {
      message.error(extractErrorMessage(err) ?? "Failed to start alert runtime");
    }
  };

  const handleStopAlertRuntime = async () => {
    if (!canEdit) return;
    try {
      const status = await stopAlertRuntime();
      setAlertRuntimeStatus(status);
      message.success("Alert runtime stopped");
      await refreshAlertsData();
    } catch (err) {
      message.error(extractErrorMessage(err) ?? "Failed to stop alert runtime");
    }
  };

  const openRuleModal = async (rule: LarkAlertRule | null) => {
    setAlertEditingRule(rule);
    setAlertRuleModalOpen(true);

    const initial: AlertRuleFormValues = rule
      ? {
          id: rule.id,
          name: rule.name,
          enabled: rule.enabled,
          entity_type: rule.entity_type,
          cron_expr: rule.cron_expr,
          event_on_create: rule.event_on_create,
          event_on_update: rule.event_on_update,
          event_on_status_change: rule.event_on_status_change,
          event_on_severity_change: rule.event_on_severity_change,
          send_via_webhook: rule.send_via_webhook,
          send_via_app: rule.send_via_app,
          recipient_employee_ids: rule.recipient_employee_ids ?? [],
          recipient_target_keys: rule.recipient_target_keys ?? [],
          max_matches_per_run: rule.max_matches_per_run ?? 50,
          card_template: rule.card_template,
          conditions:
            (rule.conditions && typeof rule.conditions === "object" && (rule.conditions as { conditions?: unknown }).conditions
              ? ((rule.conditions as { conditions?: unknown }).conditions as AlertConditionFormValue[])
              : Array.isArray(rule.conditions)
                ? (rule.conditions as AlertConditionFormValue[])
                : []) ?? [],
        }
      : {
          name: "",
          enabled: true,
          entity_type: "vulnerability",
          cron_expr: "",
          event_on_create: true,
          event_on_update: false,
          event_on_status_change: true,
          event_on_severity_change: false,
          send_via_webhook: false,
          send_via_app: true,
          recipient_employee_ids: [],
          recipient_target_keys: [],
          max_matches_per_run: 20,
          card_template: JSON.stringify(
            {
              config: { wide_screen_mode: true },
              header: {
                title: { tag: "plain_text", content: "Alert: {{ .entity_type }}" },
                template: "blue",
              },
              elements: [
                {
                  tag: "div",
                  text: {
                    tag: "lark_md",
                    content:
                      "**Entity ID**: {{ .entity.id }}\n**Status**: {{ .entity.status }}\n**Severity**: {{ .entity.severity_level }}",
                  },
                },
              ],
            },
            null,
            2,
          ),
          conditions: [],
        };

    alertRuleForm.setFieldsValue(initial);
    setAlertFields([]);
    setAlertFieldsLoading(true);
    try {
      const fields = await fetchAlertFields(initial.entity_type);
      setAlertFields(fields);
    } catch (err) {
      message.error(extractErrorMessage(err) ?? "Failed to load entity fields");
    } finally {
      setAlertFieldsLoading(false);
    }
  };

  const handleRuleEntityChange = async (entity: string) => {
    setAlertFields([]);
    setAlertFieldsLoading(true);
    try {
      const fields = await fetchAlertFields(entity);
      setAlertFields(fields);
    } catch (err) {
      message.error(extractErrorMessage(err) ?? "Failed to load entity fields");
    } finally {
      setAlertFieldsLoading(false);
    }
  };

  const handleSearchAlertRecipients = async (q: string) => {
    if (!q.trim()) {
      setAlertRecipientOptions([]);
      return;
    }
    setAlertRecipientSearchLoading(true);
    try {
      const results = await searchEmployees(q.trim());
      setAlertRecipientOptions(results ?? []);
    } catch (err) {
      message.error(extractErrorMessage(err) ?? "Failed to search employees");
    } finally {
      setAlertRecipientSearchLoading(false);
    }
  };

  const handleSaveAlertRule = async () => {
    try {
      const values = await alertRuleForm.validateFields();

      const normalizedConditions: AlertConditionFormValue[] = (values.conditions ?? []).filter(
        (c) => c && c.field && c.op,
      );
      const conditionsPayload = {
        combinator: "and",
        conditions: normalizedConditions.map((c) => {
          if (c.op === "in" || c.op === "not_in") {
            const asString = typeof c.value === "string" ? c.value : "";
            const parts = asString
              .split(",")
              .map((p) => p.trim())
              .filter(Boolean);
            return { field: c.field, op: c.op, value: parts };
          }
          return { field: c.field, op: c.op, value: c.value };
        }),
      };

      const payload: Partial<LarkAlertRule> = {
        name: values.name,
        enabled: values.enabled,
        entity_type: values.entity_type,
        cron_expr: values.cron_expr?.trim() || "",
        event_on_create: values.event_on_create,
        event_on_update: values.event_on_update,
        event_on_status_change: values.event_on_status_change,
        event_on_severity_change: values.event_on_severity_change,
        send_via_webhook: values.send_via_webhook,
        send_via_app: values.send_via_app,
        recipient_employee_ids: values.recipient_employee_ids ?? [],
        recipient_target_keys: values.recipient_target_keys ?? [],
        max_matches_per_run: values.max_matches_per_run ?? 50,
        card_template: values.card_template,
        conditions: conditionsPayload,
      };

      const hasEmployeeRecipients = Boolean(values.recipient_employee_ids && values.recipient_employee_ids.length > 0);
      const hasTargetRecipients = Boolean(values.recipient_target_keys && values.recipient_target_keys.length > 0);
      if (values.send_via_app && !hasEmployeeRecipients && !hasTargetRecipients) {
        message.error("Select at least one employee or org-aware recipient target when Send via App is enabled");
        return;
      }
      if (values.send_via_webhook && !sensitiveConfigured.lark_webhook) {
        message.error("Configure a Lark webhook in platform settings before enabling Send via Webhook");
        return;
      }
      if (
        values.send_via_app &&
        !(settings?.notifications.lark_app_id && sensitiveConfigured.lark_alert_app_secret)
      ) {
        message.error("Configure Lark app credentials in platform settings before enabling Send via App");
        return;
      }

      if (alertEditingRule?.id) {
        await updateAlertRule(alertEditingRule.id, { ...payload, id: alertEditingRule.id } as Partial<LarkAlertRule>);
        message.success("Rule updated");
      } else {
        await createAlertRule(payload);
        message.success("Rule created");
      }
      setAlertRuleModalOpen(false);
      setAlertEditingRule(null);
      await refreshAlertsData();
    } catch (err) {
      if (err && typeof err === "object" && "errorFields" in (err as object)) return;
      message.error(extractErrorMessage(err) ?? "Failed to save rule");
    }
  };

  const handleDeleteRule = async (id: number) => {
    try {
      await deleteAlertRule(id);
      message.success("Rule deleted");
      await refreshAlertsData();
    } catch (err) {
      message.error(extractErrorMessage(err) ?? "Failed to delete rule");
    }
  };

  const handleRunRuleNow = async (id: number) => {
    try {
      const run = await runAlertRuleNow(id);
      message.success(`Run finished: matched ${run.matched_count}, failed ${run.deliveries_failed}`);
      await refreshAlertsData();
    } catch (err) {
      message.error(extractErrorMessage(err) ?? "Failed to run rule");
    }
  };

  const handleViewRunDeliveries = async (run: LarkAlertRun) => {
    setSelectedRun(run);
    setDeliveriesDrawerOpen(true);
    setRunDeliveries([]);
    setRunDeliveriesLoading(true);
    try {
      const deliveries = await fetchAlertDeliveries(run.id);
      setRunDeliveries(deliveries ?? []);
    } catch (err) {
      message.error(extractErrorMessage(err) ?? "Failed to load deliveries");
    } finally {
      setRunDeliveriesLoading(false);
    }
  };

  const handlePreviewTemplate = async () => {
    try {
      const values = await alertRuleForm.validateFields(["entity_type", "card_template", "preview_entity_id"]);
      const data = await renderAlertCardTemplate({
        entity_type: values.entity_type,
        entity_id: values.preview_entity_id,
        card_template: values.card_template,
      });
      setTemplatePreview(data);
      setTemplatePreviewOpen(true);
    } catch (err) {
      if (err && typeof err === "object" && "errorFields" in (err as object)) return;
      message.error(extractErrorMessage(err) ?? "Template validation failed");
    }
  };

  const handleOpenTestSend = () => {
    setTestSendModalOpen(true);
    testSendForm.setFieldsValue({
      employee_id: undefined,
      send_webhook: false,
      card_template: JSON.stringify(
        {
          config: { wide_screen_mode: true },
          header: { title: { tag: "plain_text", content: "Test Alert" }, template: "blue" },
          elements: [{ tag: "div", text: { tag: "lark_md", content: "Hello from Security Center" } }],
        },
        null,
        2,
      ),
    });
  };

  const handleTestSend = async () => {
    try {
      const values = await testSendForm.validateFields();
      if (!values.send_webhook && !values.employee_id) {
        message.error("Select an employee or enable webhook before running a test send");
        return;
      }
      const run = await testAlertSend({
        employee_id: values.employee_id,
        send_webhook: values.send_webhook,
        card_template: values.card_template,
      });
      if (run.deliveries_failed > 0 || run.deliveries_total === 0) {
        message.error(`Test send failed: ${run.deliveries_failed}/${run.deliveries_total} deliveries failed`);
      } else {
        message.success(`Test send finished: ${run.deliveries_success}/${run.deliveries_total} deliveries sent`);
      }
      setTestSendModalOpen(false);
      await refreshAlertsData();
    } catch (err) {
      if (err && typeof err === "object" && "errorFields" in (err as object)) return;
      message.error(extractErrorMessage(err) ?? "Test send failed");
    }
  };

  useEffect(() => {
    if (activeTab !== "alert") return;
    if (!canEdit) return;
    void refreshAlertsData();
  }, [activeTab, canEdit, refreshAlertsData]);

  useEffect(() => {
    if (activeTab !== "org_sync") return;
    if (!canEdit) return;
    void refreshOrgSyncData();
  }, [activeTab, canEdit, refreshOrgSyncData]);

  const handleRunOrgSyncNow = async () => {
    if (!canEdit) return;
    if (orgSyncDirty) {
      message.warning("Save Org Sync settings before running a manual sync.");
      return;
    }
    if (!(settings?.data_sync.lark_app_id && sensitiveConfigured.org_lark_app_secret)) {
      message.error("Configure and save Org Sync Lark App ID and App Secret before running a manual sync.");
      return;
    }
    setOrgSyncingNow(true);
    try {
      const run = await syncDepartments();
      if (run.status === "running") {
        message.success("Org sync started. Check runs for progress.");
      } else {
        message.success(`Org sync completed: ${run.departments_upserted} departments, ${run.employees_upserted} employees`);
      }
      await refreshOrgSyncData();
    } catch (err) {
      message.error(extractErrorMessage(err) ?? "Org sync failed");
      await refreshOrgSyncData();
    } finally {
      setOrgSyncingNow(false);
    }
  };

  const handleEmployeeSearch = async (query: string) => {
    if (!canEdit) return;
    const trimmed = query.trim();
    if (!trimmed) {
      setEmployeeSearchResults([]);
      return;
    }
    setEmployeeSearchLoading(true);
    try {
      const results = await searchEmployees(trimmed);
      setEmployeeSearchResults(results ?? []);
    } catch (err) {
      message.error(extractErrorMessage(err) ?? "Failed to search employees");
    } finally {
      setEmployeeSearchLoading(false);
    }
  };

  const latestRun = orgSyncRuns[0];
  const orgSyncSettingsConfigured = Boolean(
    settings?.data_sync.org_sync_enabled &&
      settings?.data_sync.lark_app_id &&
      sensitiveConfigured.org_lark_app_secret,
  );
  const orgSyncRuntimeHealthy = Boolean(orgRuntimeStatus?.scheduler_running && orgRuntimeStatus?.lark_configured && !orgRuntimeStatus?.last_error);
  const lastSyncDisplay = orgRuntimeStatus?.last_successful_sync_at || orgRuntimeStatus?.last_sync_at || latestRun?.finished_at || latestRun?.started_at || "—";
  const lastSyncResult = latestRun
    ? `${latestRun.departments_upserted}/${latestRun.departments_fetched} dept • ${latestRun.employees_upserted}/${latestRun.employees_fetched} emp`
    : "—";
  const orgSyncFreshness: OrgSyncFreshnessSummary = useMemo(
    () => deriveOrgSyncFreshness(orgRuntimeStatus, orgSyncRuns),
    [orgRuntimeStatus, orgSyncRuns],
  );
  const orgSyncPickerReadsBlocked = Boolean(orgRuntimeStatus?.blocking_scopes?.includes("picker_reads"));
  const alertRoutingBoundary: AlertRoutingBoundarySummary = useMemo(
    () => describeAlertRoutingBoundary(settings?.notifications),
    [settings?.notifications],
  );
  const alertOpenIDAppMismatch = Boolean(
    settings?.notifications.lark_alerts &&
      (settings.notifications.lark_receive_id_type ?? "open_id") === "open_id" &&
      settings.notifications.lark_app_id &&
      settings.data_sync.lark_app_id &&
      settings.notifications.lark_app_id !== settings.data_sync.lark_app_id,
  );

  const orgDepartmentColumns: ColumnsType<Department> = useMemo(
    () => [
      {
        title: "Name",
        dataIndex: "name",
        key: "name",
      },
      {
        title: "Lark Dept ID",
        dataIndex: "lark_department_id",
        key: "lark_department_id",
        width: 240,
      },
      {
        title: "Parent",
        dataIndex: "parent_id",
        key: "parent_id",
        width: 160,
        render: (value: string) => value || "—",
      },
      {
        title: "Leader",
        dataIndex: "leader_id",
        key: "leader_id",
        width: 160,
        render: (value: string) => value || "—",
      },
      {
        title: "Status",
        dataIndex: "status",
        key: "status",
        width: 120,
        render: (value: string) => <Tag color={value === "active" ? "green" : "default"}>{value || "—"}</Tag>,
      },
    ],
    [],
  );

  const orgSyncRunColumns: ColumnsType<OrgSyncRun> = useMemo(
    () => [
      {
        title: "Status",
        key: "status",
        width: 120,
        render: (_, run) => (
          <Tag color={run.status === "success" ? "green" : run.status === "error" ? "red" : "blue"}>
            {run.status.toUpperCase()}
          </Tag>
        ),
      },
      {
        title: "Trigger",
        dataIndex: "trigger_source",
        key: "trigger_source",
        width: 120,
      },
      {
        title: "Started",
        dataIndex: "started_at",
        key: "started_at",
        width: 200,
      },
      {
        title: "Finished",
        dataIndex: "finished_at",
        key: "finished_at",
        width: 200,
        render: (value: string | undefined) => value || "—",
      },
      {
        title: "Dept",
        key: "departments",
        width: 160,
        render: (_, run) => `${run.departments_upserted}/${run.departments_fetched}`,
      },
      {
        title: "Emp",
        key: "employees",
        width: 160,
        render: (_, run) => `${run.employees_upserted}/${run.employees_fetched}`,
      },
      {
        title: "Steps",
        key: "steps",
        render: (_, run) => {
          if (!run.step_status) return "—";
          const order = [
            "departments_fetch",
            "departments_upsert",
            "employees_fetch",
            "employees_upsert",
          ];
          const labels: Record<string, string> = {
            departments_fetch: "Dept Fetch",
            departments_upsert: "Dept Upsert",
            employees_fetch: "Emp Fetch",
            employees_upsert: "Emp Upsert",
          };
          return (
            <Space wrap>
              {order.map((key) => {
                const step = run.step_status?.[key];
                if (!step?.status) return null;
                const status = String(step.status);
                const color =
                  status === "success" ? "green" : status === "error" ? "red" : status === "partial" ? "orange" : "blue";
                const countSuffix = typeof step.count === "number" ? ` (${step.count})` : "";
                return (
                  <Tag key={key} color={color}>
                    {labels[key]} {status.toUpperCase()}{countSuffix}
                  </Tag>
                );
              })}
            </Space>
          );
        },
      },
    ],
    []
  );

  const lastUpdated = useMemo(() => {
    if (!settings?.updated_at) return "Not updated yet";
    const date = new Date(settings.updated_at);
    if (Number.isNaN(date.getTime())) return settings.updated_at;
    return date.toLocaleString();
  }, [settings]);

  const versionTag = useMemo(() => {
    const cfgVersion = settings?.version ?? 1;
    const serviceVersion = versionInfo?.version;
    return serviceVersion ? `service ${serviceVersion} · cfg v${cfgVersion}` : `v${cfgVersion}`;
  }, [settings?.version, versionInfo?.version]);
  const healthTagColor = getStatusColor(health?.status ?? "unknown");

  const tabItems: TabsProps["items"] = [
    {
      key: "platform",
      label: renderTabLabel("Platform Identity", platformDirty, saving.platform, savedAt.platform),
      forceRender: true,
      children: (
        <Space direction="vertical" size={16} style={{ width: "100%" }}>
          <Card title="Brand Settings">
            {platformDirty ? (
              <Alert
                type="info"
                showIcon
                message="Unsaved changes"
                description={<ChangeList entries={platformChanges} />}
                style={{ marginBottom: 16 }}
              />
            ) : null}
            <Form layout="vertical" form={platformForm} onFinish={handlePlatformSave} disabled={!canEdit}>
              <Form.Item
                label="Display Name"
                name="display_name"
                rules={[{ required: true, message: "Display name is required" }]}
              >
                <Input.TextArea
                  placeholder="Cloud Security Center"
                  title={displayNameValue}
                  autoSize={{ minRows: 1, maxRows: 3 }}
                />
              </Form.Item>
              <Form.Item label="Support Email" name="support_email" rules={[{ type: "email", message: "Enter a valid email" }]}>
                <Input placeholder="secops@example.com" />
              </Form.Item>
              <Form.Item label="Default Timezone" name="default_timezone">
                <Input placeholder="UTC" />
              </Form.Item>
              <Form.Item label="Logo URL" name="logo_url">
                <Input placeholder="https://assets.example.com/logo.svg" />
              </Form.Item>
              <Form.Item name="maintenance_mode" label="Maintenance Mode" valuePropName="checked">
                <Switch />
              </Form.Item>
              <Form.Item label="Change Note" name="changeNote">
                <Input.TextArea rows={2} maxLength={120} placeholder="Optional context for the audit log" />
              </Form.Item>
              <Form.Item>
                <Space>
                  <Button type="primary" loading={saving.platform} onClick={() => platformForm.submit()} disabled={!canEdit}>
                    Save Platform Settings
                  </Button>
                  {platformDirty ? (
                    <Button
                      onClick={() => settings && platformForm.setFieldsValue({ ...settings.platform, changeNote: "" })}
                      disabled={!canEdit}
                    >
                      Reset
                    </Button>
                  ) : null}
                </Space>
              </Form.Item>
            </Form>
          </Card>
        </Space>
      ),
    },
    {
      key: "alert",
      label: renderTabLabel("Alert", notificationDirty, saving.notifications, savedAt.notifications),
      forceRender: true,
      children: (
        <Space direction="vertical" size={16} style={{ width: "100%" }}>
          <Card title="Notification Defaults">
            {notificationDirty ? (
              <Alert
                type="info"
                showIcon
                message="Unsaved notification changes"
                description={<ChangeList entries={notificationChanges} />}
                style={{ marginBottom: 16 }}
              />
            ) : null}
            <Form layout="vertical" form={notificationForm} onFinish={handleNotificationSave} disabled={!canEdit}>
              <Form.Item name="email_alerts" label="Email Alerts" valuePropName="checked">
                <Switch />
              </Form.Item>
              <Form.Item label="Email From Address" name="email_from_address" rules={[{ type: "email", message: "Enter a valid email" }]}>
                <Input placeholder="alerts@example.com" />
              </Form.Item>
              <Form.Item name="lark_alerts" label="Lark Alerts" valuePropName="checked">
                <Switch />
              </Form.Item>
              <MaskedSecretField
                name="lark_webhook"
                label="Lark Incoming Webhook URL"
                placeholder="https://open.feishu.cn/open-apis/bot/v2/hook/..."
                onReveal={handleSensitiveReveal}
                configured={sensitiveConfigured.lark_webhook}
              />
              <Form.Item label="Lark App ID" name="lark_app_id">
                <Input placeholder="cli_a123..." />
              </Form.Item>
              <MaskedSecretField
                name="lark_app_secret"
                label="Lark App Secret"
                placeholder="******"
                onReveal={handleSensitiveReveal}
                configured={sensitiveConfigured.lark_alert_app_secret}
              />
              <Form.Item label="Lark receive_id_type" name="lark_receive_id_type">
                <Select
                  options={[
                    { value: "open_id", label: "open_id" },
                    { value: "email", label: "email" },
                  ]}
                />
              </Form.Item>
              <Text type="secondary" style={{ display: "block", marginTop: -8, marginBottom: 16 }}>
                Feishu directory sync currently persists `open_id` and email for recipients. `user_id` is intentionally hidden until the directory contract stores it explicitly.
              </Text>
              <MaskedSecretField
                name="incident_webhook"
                label="Incident Webhook URL"
                placeholder="https://example.com/webhook"
                onReveal={handleSensitiveReveal}
                configured={sensitiveConfigured.incident_webhook}
              />
              <Form.Item label="Severity Threshold" name="severity_threshold">
                <Select options={severityOptions.map((value) => ({ value, label: value.toUpperCase() }))} />
              </Form.Item>
              <Form.Item name="digest_enabled" label="Daily Digest" valuePropName="checked">
                <Switch />
              </Form.Item>
              <Divider orientation="left">Vulnerability SLA Reminders</Divider>
              <Form.Item name="vulnerability_sla_reminders_enabled" label="SLA Reminders" valuePropName="checked">
                <Switch />
              </Form.Item>
              <Row gutter={16}>
                <Col xs={24} md={12}>
                  <Form.Item
                    label="Due Soon Before"
                    name="vulnerability_sla_due_soon_before_hours"
                    rules={[
                      {
                        validator: (_, value) =>
                          isPositiveInteger(value)
                            ? Promise.resolve()
                            : Promise.reject(new Error("Enter a positive whole number of hours")),
                      },
                    ]}
                  >
                    <InputNumber min={1} precision={0} addonAfter="hours" style={{ width: "100%" }} />
                  </Form.Item>
                </Col>
                <Col xs={24} md={12}>
                  <Form.Item
                    label="Overdue Repeat"
                    name="vulnerability_sla_overdue_repeat_hours"
                    rules={[
                      {
                        validator: (_, value) =>
                          isPositiveInteger(value)
                            ? Promise.resolve()
                            : Promise.reject(new Error("Enter a positive whole number of hours")),
                      },
                    ]}
                  >
                    <InputNumber min={1} precision={0} addonAfter="hours" style={{ width: "100%" }} />
                  </Form.Item>
                </Col>
              </Row>
              <Form.Item label="Change Note" name="changeNote">
                <Input.TextArea rows={2} maxLength={120} placeholder="Optional context for the audit log" />
              </Form.Item>
              <Form.Item>
                <Space>
                  <Button
                    type="primary"
                    loading={saving.notifications}
                    onClick={() => notificationForm.submit()}
                    disabled={!canEdit}
                  >
                    Save Notification Defaults
                  </Button>
                  {notificationDirty ? (
                    <Button
                      onClick={() =>
                        settings &&
                        notificationForm.setFieldsValue({
                          ...normalizeNotificationSettings(settings.notifications),
                          lark_webhook: "",
                          lark_app_secret: "",
                          incident_webhook: "",
                          changeNote: "",
                        })
                      }
                      disabled={!canEdit}
                    >
                      Reset
                    </Button>
                  ) : null}
                </Space>
              </Form.Item>
            </Form>
          </Card>

          <Card
            title="Lark Alerts Observability"
            extra={
              <Space>
                <Button icon={<ReloadOutlined />} onClick={refreshAlertsData} loading={alertLoading} disabled={!canEdit}>
                  Refresh
                </Button>
                {alertRuntimeStatus?.scheduler_running ? (
                  <Popconfirm
                    title="Stop alert runtime?"
                    description="Stops scheduled polling and cron triggers until restarted."
                    okText="Stop"
                    okButtonProps={{ danger: true }}
                    onConfirm={handleStopAlertRuntime}
                  >
                    <Button danger disabled={!canEdit}>
                      Stop Runtime
                    </Button>
                  </Popconfirm>
                ) : (
                  <Button type="primary" onClick={handleStartAlertRuntime} disabled={!canEdit}>
                    Start Runtime
                  </Button>
                )}
                <Button onClick={handleRefreshAlertRuntime} disabled={!canEdit}>
                  Refresh Runtime
                </Button>
                <Button type="primary" onClick={handleOpenTestSend} disabled={!canEdit}>
                  Test Send
                </Button>
              </Space>
            }
          >
            {!canEdit ? (
              <Alert type="info" showIcon message="Requires system:manage_settings permission to view and manage alerts." />
            ) : (
              <Space direction="vertical" size={16} style={{ width: "100%" }}>
                <Alert
                  type={alertRoutingBoundary.alerts_enabled ? "info" : "warning"}
                  showIcon
                  message={alertRoutingBoundary.label}
                  description={
                    <Space direction="vertical" size={2}>
                      <Text>{alertRoutingBoundary.description}</Text>
                      <Text type="secondary">{alertRoutingBoundary.credential_boundary}</Text>
                      <Text type="secondary">{alertRoutingBoundary.employee_delivery}</Text>
                      <Text type="secondary">
                        {`Webhook delivery ${alertRoutingBoundary.webhook_delivery_ready ? "ready" : "not configured"} · receive_id_type ${alertRoutingBoundary.receive_id_type}`}
                      </Text>
                    </Space>
                  }
                />
                {!settings?.notifications.lark_alerts ? (
                  <Alert type="warning" showIcon message="Lark alerts are currently disabled. Enable them above to send alerts." />
                ) : null}
                {alertOpenIDAppMismatch ? (
                  <Alert
                    type="warning"
                    showIcon
                    message="open_id delivery is using a different Feishu app than Org Sync"
                    description="Synced employee open_id values are app-scoped. Use the same Feishu app for Org Sync and alert delivery when receive_id_type is open_id, or switch alert receive_id_type to email."
                  />
                ) : null}
                <Descriptions size="small" column={2} bordered>
                  <Descriptions.Item label="Scheduler Running">
                    <Tag color={alertRuntimeStatus?.scheduler_running ? "green" : "default"}>
                      {alertRuntimeStatus?.scheduler_running ? "Running" : "Stopped"}
                    </Tag>
                  </Descriptions.Item>
                  <Descriptions.Item label="Scheduled Rules">{alertRuntimeStatus?.scheduled_rules ?? 0}</Descriptions.Item>
                  <Descriptions.Item label="Webhook Configured">
                    <Tag color={sensitiveConfigured.lark_webhook ? "green" : "red"}>
                      {sensitiveConfigured.lark_webhook ? "Yes" : "No"}
                    </Tag>
                  </Descriptions.Item>
                  <Descriptions.Item label="App Credentials Configured">
                    <Tag color={(settings?.notifications.lark_app_id && sensitiveConfigured.lark_alert_app_secret) ? "green" : "red"}>
                      {(settings?.notifications.lark_app_id && sensitiveConfigured.lark_alert_app_secret) ? "Yes" : "No"}
                    </Tag>
                  </Descriptions.Item>
                  <Descriptions.Item label="Routing Boundary">
                    <Tag color="blue">{alertRoutingBoundary.boundary_mode.toUpperCase()}</Tag>
                  </Descriptions.Item>
                  <Descriptions.Item label="Employee Delivery">{alertRoutingBoundary.employee_delivery}</Descriptions.Item>
                  <Descriptions.Item label="receive_id_type">{settings?.notifications.lark_receive_id_type || "open_id"}</Descriptions.Item>
                  <Descriptions.Item label="Webhook Delivery">{alertRoutingBoundary.webhook_delivery}</Descriptions.Item>
                  <Descriptions.Item label="Last Tick">{alertRuntimeStatus?.last_tick_at || "—"}</Descriptions.Item>
                  <Descriptions.Item label="Last Error" span={2}>
                    {alertRuntimeStatus?.last_error ? (
                      <Text type="danger">
                        {alertRuntimeStatus.last_error}
                        {alertRuntimeStatus.last_error_at ? ` (${alertRuntimeStatus.last_error_at})` : ""}
                      </Text>
                    ) : (
                      "—"
                    )}
                  </Descriptions.Item>
                </Descriptions>

                <div>
                  <Text strong>Recent Runs</Text>
                  <Divider style={{ margin: "8px 0 12px" }} />
                  <Table<LarkAlertRun>
                    size="small"
                    rowKey="id"
                    loading={alertLoading}
                    dataSource={alertRuns}
                    pagination={{ pageSize: 8 }}
                    columns={[
                      {
                        title: "Status",
                        dataIndex: "status",
                        key: "status",
                        width: 110,
                        render: (v: LarkAlertRun["status"]) => (
                          <Tag color={v === "success" ? "green" : v === "error" ? "red" : "blue"}>{v.toUpperCase()}</Tag>
                        ),
                      },
                      { title: "Trigger", dataIndex: "trigger_source", key: "trigger_source", width: 90 },
                      { title: "Rule", dataIndex: "rule_id", key: "rule_id", width: 80 },
                      { title: "Started", dataIndex: "started_at", key: "started_at", width: 200 },
                      { title: "Matched", dataIndex: "matched_count", key: "matched_count", width: 90 },
                      { title: "Failed", dataIndex: "deliveries_failed", key: "deliveries_failed", width: 80 },
                      {
                        title: "Actions",
                        key: "actions",
                        width: 120,
                        render: (_, run) => (
                          <Button size="small" onClick={() => handleViewRunDeliveries(run)}>
                            Deliveries
                          </Button>
                        ),
                      },
                    ]}
                  />
                </div>
              </Space>
            )}
          </Card>

          <Card
            title="Lark Alert Rules"
            extra={
              <Space>
                <Button onClick={() => openRuleModal(null)} disabled={!canEdit}>
                  New Rule
                </Button>
              </Space>
            }
          >
            {!canEdit ? (
              <Empty description="No permission to manage rules" />
            ) : (
              <Table<LarkAlertRule>
                size="small"
                rowKey="id"
                loading={alertLoading}
                dataSource={alertRules}
                pagination={{ pageSize: 8 }}
                columns={[
                  { title: "Name", dataIndex: "name", key: "name" },
                  { title: "Entity", dataIndex: "entity_type", key: "entity_type", width: 120 },
                  {
                    title: "Enabled",
                    dataIndex: "enabled",
                    key: "enabled",
                    width: 90,
                    render: (v: boolean) => <Tag color={v ? "green" : "default"}>{v ? "Yes" : "No"}</Tag>,
                  },
                  {
                    title: "Triggers",
                    key: "triggers",
                    render: (_, rule) => (
                      <Text type="secondary">
                        {rule.cron_expr ? "cron " : ""}
                        {rule.event_on_create ? "create " : ""}
                        {rule.event_on_update ? "update " : ""}
                        {rule.event_on_status_change ? "status " : ""}
                        {rule.event_on_severity_change ? "severity " : ""}
                      </Text>
                    ),
                  },
                  {
                    title: "Recipients",
                    key: "recipients",
                    render: (_, rule) => (
                      <Space size={[4, 4]} wrap>
                        {(rule.recipient_employee_ids?.length ?? 0) > 0 ? (
                          <Tag color="blue">{`${rule.recipient_employee_ids?.length ?? 0} employees`}</Tag>
                        ) : null}
                        {(rule.recipient_target_keys ?? []).map((target) => (
                          <Tag key={target} color={target === "entity_department" ? "purple" : target.startsWith("entity_") ? "cyan" : "geekblue"}>
                            {target.replace(/_/g, " ")}
                          </Tag>
                        ))}
                        {!(rule.recipient_employee_ids?.length ?? 0) && !(rule.recipient_target_keys?.length ?? 0) ? (
                          <Text type="secondary">—</Text>
                        ) : null}
                      </Space>
                    ),
                  },
                  { title: "Last Run", dataIndex: "last_run_at", key: "last_run_at", width: 200 },
                  {
                    title: "Actions",
                    key: "actions",
                    width: 220,
                    render: (_, rule) => (
                      <Space>
                        <Button size="small" onClick={() => openRuleModal(rule)}>
                          Edit
                        </Button>
                        <Button size="small" onClick={() => handleRunRuleNow(rule.id)}>
                          Run Now
                        </Button>
                        <Popconfirm
                          title="Delete rule?"
                          okText="Delete"
                          okButtonProps={{ danger: true }}
                          onConfirm={() => handleDeleteRule(rule.id)}
                        >
                          <Button size="small" danger>
                            Delete
                          </Button>
                        </Popconfirm>
                      </Space>
                    ),
                  },
                ]}
              />
            )}
          </Card>
        </Space>
      ),
    },
    {
      key: "authentication",
      label: renderTabLabel("Authentication Policy", authDirty, saving.authentication, savedAt.authentication),
      forceRender: true,
      children: (
        <Card title="Authentication & Security">
          {authDirty ? (
            <Alert
              type="info"
              showIcon
              message="Unsaved authentication changes"
              description={<ChangeList entries={authChanges} />}
              style={{ marginBottom: 16 }}
            />
          ) : null}
          <Form layout="vertical" form={authForm} onFinish={handleAuthSave} disabled={!canEdit}>
            <Form.Item
              label="SSO Provider"
              name="sso_provider"
              rules={[{ required: true, message: "Select an SSO provider" }]}
            >
              <Select
                options={[
                  { value: "google", label: "Google OAuth (Legacy)" },
                  { value: "auth0", label: "Auth0 (Google SSO)" },
                ]}
              />
            </Form.Item>
            {isAuth0 ? (
              <>
                <Form.Item
                  label="Auth0 Domain"
                  name="auth0_domain"
                  rules={[{ required: isAuth0, message: "Auth0 domain is required" }]}
                >
                  <Input placeholder="your-tenant.auth0.com" />
                </Form.Item>
                <Form.Item
                  label="Auth0 Client ID"
                  name="auth0_client_id"
                  rules={[{ required: isAuth0, message: "Auth0 client ID is required" }]}
                >
                  <Input placeholder="Client ID from Auth0 dashboard" />
                </Form.Item>
	                <MaskedSecretField
	                  name="auth0_client_secret"
	                  label="Auth0 Client Secret"
	                  placeholder="Paste Auth0 client secret"
	                  required={isAuth0}
	                  onReveal={handleSensitiveReveal}
	                  configured={sensitiveConfigured.auth0_client_secret}
	                />
                <Form.Item label="Auth0 Audience (Optional)" name="auth0_audience">
                  <Input placeholder="https://api.your-app.com" />
                </Form.Item>
              </>
            ) : null}
            <Form.Item name="enforce_sso" label="Enforce SSO" valuePropName="checked">
              <Switch />
            </Form.Item>
            <Form.Item label="Default Role" name="default_role">
              <Input placeholder="viewer" />
            </Form.Item>
            <Form.Item label="Session Timeout (minutes)" name="session_timeout_minutes" rules={[{ required: true, message: "Session timeout is required" }]}>
              <InputNumber min={15} max={720} style={{ width: "100%" }} />
            </Form.Item>
            <Alert
              type="info"
              showIcon
              message="Local-user login is not a normal production path"
              description="Enterprise rollout keeps username/password login disabled. Break-glass access, if ever approved, must stay outside the normal settings surface and follow the dedicated deployment policy."
              style={{ marginBottom: 16 }}
            />
            <Form.Item name="mfa_required" label="Require MFA" valuePropName="checked">
              <Switch />
            </Form.Item>
            <Form.Item label="Change Note" name="changeNote">
              <Input.TextArea rows={2} maxLength={120} placeholder="Optional context for the audit log" />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" loading={saving.authentication} onClick={() => authForm.submit()} disabled={!canEdit}>
                  Save Authentication Settings
                </Button>
                {authDirty ? (
                  <Button
                    onClick={() => settings && authForm.setFieldsValue({ ...settings.authentication, auth0_client_secret: "", changeNote: "" })}
                    disabled={!canEdit}
                  >
                    Reset
                  </Button>
                ) : null}
              </Space>
            </Form.Item>
          </Form>
        </Card>
      ),
    },
    {
      key: "org_sync",
      label: renderTabLabel("Org Sync", orgSyncDirty, saving.org_sync, savedAt.org_sync),
      forceRender: true,
      children: (
        <Space direction="vertical" size={16} style={{ width: "100%" }}>
          <Card title="Organization Sync">
            {orgSyncDirty ? (
              <Alert
                type="info"
                showIcon
                message="Unsaved org sync changes"
                description={<ChangeList entries={orgSyncChanges} />}
                style={{ marginBottom: 16 }}
              />
            ) : null}
            <Form
              layout="vertical"
              form={orgSyncForm}
              onFinish={handleOrgSyncSave}
              onFinishFailed={(errorInfo) => {
                console.error('Form validation failed:', errorInfo);
                const firstError = errorInfo.errorFields?.[0]?.errors?.[0];
                if (firstError) {
                  message.error(firstError);
                }
              }}
              disabled={!canEdit}
            >
              <Form.Item name="org_sync_enabled" label="Org Sync Enabled" valuePropName="checked">
                <Switch />
              </Form.Item>
              {orgSyncEnabled && !sensitiveConfigured.org_lark_app_secret ? (
                <Alert
                  type="warning"
                  showIcon
                  message="Lark credentials required"
                  description="To enable organization sync, you must provide both Lark App ID and App Secret. These credentials stay in the org-sync boundary and are separate from alert-delivery settings."
                  style={{ marginBottom: 16 }}
                />
              ) : null}
              <Form.Item label="Org Provider" name="org_provider">
                <Input placeholder="feishu" />
              </Form.Item>
              <Form.Item label="Org Sync Cron" name="org_sync_cron">
                <Input placeholder="0 * * * *" />
              </Form.Item>
              <Row gutter={16}>
                <Col xs={24} md={12}>
                  <Form.Item
                    label="Stale after (hours)"
                    name="org_sync_stale_after_hours"
                    rules={[
                      { required: true, message: "Stale threshold is required" },
                      {
                        type: "number",
                        min: 1,
                        message: "Stale threshold must be a positive integer",
                      },
                      {
                        validator: (_, value) => {
                          const expiredAfter = orgSyncForm.getFieldValue("org_sync_expired_after_hours");
                          if (typeof value !== "number" || typeof expiredAfter !== "number") {
                            return Promise.resolve();
                          }
                          if (value >= expiredAfter) {
                            return Promise.reject(new Error("Stale threshold must be less than expire threshold"));
                          }
                          return Promise.resolve();
                        },
                      },
                    ]}
                  >
                    <InputNumber min={1} precision={0} style={{ width: "100%" }} />
                  </Form.Item>
                </Col>
                <Col xs={24} md={12}>
                  <Form.Item
                    label="Expire after (hours)"
                    name="org_sync_expired_after_hours"
                    rules={[
                      { required: true, message: "Expire threshold is required" },
                      {
                        type: "number",
                        min: 1,
                        message: "Expire threshold must be a positive integer",
                      },
                      {
                        validator: (_, value) => {
                          const staleAfter = orgSyncForm.getFieldValue("org_sync_stale_after_hours");
                          if (typeof value !== "number" || typeof staleAfter !== "number") {
                            return Promise.resolve();
                          }
                          if (staleAfter >= value) {
                            return Promise.reject(new Error("Expire threshold must be greater than stale threshold"));
                          }
                          return Promise.resolve();
                        },
                      },
                    ]}
                  >
                    <InputNumber min={1} precision={0} style={{ width: "100%" }} />
                  </Form.Item>
                </Col>
              </Row>
              <Form.Item
                label="Lark App ID"
                name="lark_app_id"
                rules={
                  orgSyncEnabled
                    ? [
                        { required: true, message: "Lark App ID is required when org sync is enabled" },
                      ]
                    : undefined
                }
              >
                <Input placeholder="cli_..." />
              </Form.Item>
              <MaskedSecretField
                name="lark_app_secret"
                label="Lark App Secret"
                placeholder="Enter app secret (required when org sync is enabled)"
                onReveal={handleSensitiveReveal}
                configured={sensitiveConfigured.org_lark_app_secret}
                required={Boolean(orgSyncEnabled)}
              />
              <Form.Item label="Change Note" name="changeNote">
                <Input.TextArea rows={2} maxLength={120} placeholder="Optional context for the audit log" />
              </Form.Item>
              <Form.Item>
                <Space>
                  <Button type="primary" loading={saving.org_sync} onClick={() => orgSyncForm.submit()} disabled={!canEdit}>
                    Save Org Sync Settings
                  </Button>
                  {orgSyncDirty ? (
                    <Button
                      onClick={() =>
                        settings &&
                        orgSyncForm.setFieldsValue({
                          org_sync_enabled: settings.data_sync.org_sync_enabled,
                          org_provider: settings.data_sync.org_provider,
                          org_sync_cron: settings.data_sync.org_sync_cron,
                          org_sync_stale_after_hours: settings.data_sync.org_sync_stale_after_hours,
                          org_sync_expired_after_hours: settings.data_sync.org_sync_expired_after_hours,
                          lark_app_id: settings.data_sync.lark_app_id,
                          lark_app_secret: "",
                          changeNote: "",
                        })
                      }
                      disabled={!canEdit}
                    >
                      Reset
                    </Button>
                  ) : null}
                </Space>
              </Form.Item>
            </Form>
          </Card>

          <Card
            title="Org Sync Observability"
            extra={
              <Space>
                <Button icon={<ReloadOutlined />} onClick={refreshOrgSyncData} loading={orgSyncLoading} disabled={!canEdit}>
                  Refresh
                </Button>
                <Button type="primary" onClick={handleRunOrgSyncNow} loading={orgSyncingNow} disabled={!canEdit}>
                  Sync Now
                </Button>
              </Space>
            }
          >
            {!canEdit ? (
              <Alert type="info" showIcon message="Requires system:manage_settings permission to view org sync status and data." />
            ) : (
              <Space direction="vertical" size={16} style={{ width: "100%" }}>
                <Alert
                  type="info"
                  showIcon
                  message={orgSyncFreshness.label}
                  description={
                    <Space direction="vertical" size={2}>
                      <Text>{orgSyncFreshness.description}</Text>
                      <Text type="secondary">
                        {orgSyncFreshness.last_good_sync_at
                          ? `Last trusted sync: ${orgSyncFreshness.last_good_sync_at}`
                          : "No trusted sync is available yet."}
                      </Text>
                      <Text type="secondary">
                        {orgSyncFreshness.state === "fresh"
                          ? "Freshness window: trusted within 24h."
                          : orgSyncFreshness.state === "stale"
                            ? "Degraded mode: bounded last-good snapshot may be used for picker/read flows, but authorization must not expand."
                            : "Blocked mode: snapshots older than the trusted window are not trusted for sensitive decisions."}
                      </Text>
                    </Space>
                  }
                />
                <Alert
                  type="info"
                  showIcon
                  message="Split Lark boundary"
                  description="Org Sync keeps Feishu directory sync credentials in the data-sync boundary; alert delivery stays in the notification boundary. The two credential sets are intentionally separate."
                />
                {settings?.data_sync.org_sync_enabled && !orgSyncSettingsConfigured ? (
                  <Alert
                    type="warning"
                    showIcon
                    message="Org Sync is enabled but credentials are incomplete"
                    description="Save a Lark App ID and App Secret in Org Sync settings before starting runtime. Manual Sync Now can also use saved credentials while the scheduler is disabled."
                  />
                ) : null}
                {orgSyncSettingsConfigured && !orgSyncRuntimeHealthy ? (
                  <Alert
                    type={orgRuntimeStatus?.last_error ? "warning" : "info"}
                    showIcon
                    message={orgRuntimeStatus?.last_error ? "Org Sync runtime needs attention" : "Org Sync runtime is not fully running"}
                    description={
                      orgRuntimeStatus?.last_error
                        ? orgRuntimeStatus.last_error
                        : "Settings credentials are saved, but the scheduler or runtime client is not active yet."
                    }
                  />
                ) : null}
                {latestRun?.status === "error" && latestRun.error_message ? (
                  <Alert
                    type="warning"
                    showIcon
                    message="Latest manual sync failed"
                    description={latestRun.error_message}
                  />
                ) : null}
                <Descriptions size="small" column={2} bordered>
                  <Descriptions.Item label="Settings Configured">
                    <Tag color={orgSyncSettingsConfigured ? "green" : "red"}>
                      {orgSyncSettingsConfigured ? "Yes" : "No"}
                    </Tag>
                  </Descriptions.Item>
                  <Descriptions.Item label="Freshness">
                    <Tag
                      color={
                        orgSyncFreshness.state === "fresh"
                          ? "green"
                          : orgSyncFreshness.state === "stale"
                            ? "orange"
                            : orgSyncFreshness.state === "expired"
                              ? "red"
                              : "default"
                      }
                    >
                      {orgSyncFreshness.label}
                    </Tag>
                  </Descriptions.Item>
                  <Descriptions.Item label="Snapshot Trust">
                    <Tag color={orgSyncFreshness.trust_mode === "trusted_snapshot" ? "green" : orgSyncFreshness.trust_mode === "degraded_snapshot" ? "orange" : "red"}>
                      {orgSyncFreshness.trust_mode.replace(/_/g, " ")}
                    </Tag>
                  </Descriptions.Item>
                  <Descriptions.Item label="Scheduler">
                    <Tag color={orgRuntimeStatus?.scheduler_running ? "green" : "default"}>
                      {orgRuntimeStatus?.scheduler_running ? "Running" : "Stopped"}
                    </Tag>
                  </Descriptions.Item>
                  <Descriptions.Item label="Runtime Client">
                    <Tag color={orgRuntimeStatus?.lark_configured ? "green" : "default"}>
                      {orgRuntimeStatus?.lark_configured ? "Yes" : "No"}
                    </Tag>
                  </Descriptions.Item>
                  <Descriptions.Item label="Sync Running">
                    <Tag color={orgRuntimeStatus?.sync_running ? "blue" : "default"}>
                      {orgRuntimeStatus?.sync_running ? "In Progress" : "Idle"}
                    </Tag>
                  </Descriptions.Item>
                  <Descriptions.Item label="Degraded Mode">
                    {orgSyncFreshness.state === "fresh"
                      ? "Not active"
                      : orgSyncFreshness.state === "stale"
                        ? "Bounded last-good snapshot only"
                        : orgSyncFreshness.state === "expired"
                          ? "Blocked until a fresh sync"
                          : "Unavailable until first sync"}
                  </Descriptions.Item>
                  <Descriptions.Item label="Cron">{orgRuntimeStatus?.current_cron || "—"}</Descriptions.Item>
                  <Descriptions.Item label="Next Sync">{orgRuntimeStatus?.next_sync_at || "—"}</Descriptions.Item>
                  <Descriptions.Item label="Last Sync">{lastSyncDisplay}</Descriptions.Item>
                  <Descriptions.Item label="Last Trusted Sync">{orgSyncFreshness.last_good_sync_at || "—"}</Descriptions.Item>
                  <Descriptions.Item label="Last Run Status">
                    {latestRun?.status ? (
                      <Tag color={getStatusColor(latestRun.status)}>{latestRun.status.toUpperCase()}</Tag>
                    ) : (
                      "—"
                    )}
                  </Descriptions.Item>
                  <Descriptions.Item label="Stored Departments">{orgDepartments.length}</Descriptions.Item>
                  <Descriptions.Item label="Last Result">{lastSyncResult}</Descriptions.Item>
                  <Descriptions.Item label="Last Error" span={2}>
                    {orgRuntimeStatus?.last_error ? (
                      <Text type="danger">
                        {orgRuntimeStatus.last_error}
                        {orgRuntimeStatus.last_error_at ? ` (${orgRuntimeStatus.last_error_at})` : ""}
                      </Text>
                    ) : (
                      "—"
                    )}
                  </Descriptions.Item>
                </Descriptions>

                <div>
                  <Text strong>Recent Runs</Text>
                  <Divider style={{ margin: "8px 0 12px" }} />
                  <Table<OrgSyncRun>
                    rowKey={(run) => String(run.id)}
                    columns={orgSyncRunColumns}
                    dataSource={orgSyncRuns.slice(0, 10)}
                    pagination={false}
                    size="small"
                    locale={{ emptyText: "No sync runs yet" }}
                    expandable={{
                      expandedRowRender: (run) =>
                        run.error_message ? <Text type="danger">{run.error_message}</Text> : null,
                      rowExpandable: (run) => Boolean(run.error_message),
                    }}
                  />
                </div>
              </Space>
            )}
          </Card>

          <Card title="Departments & Employees">
            {!canEdit ? (
              <Alert type="info" showIcon message="Requires system:manage_settings permission to view departments and employees." />
            ) : (
              <Space direction="vertical" size={16} style={{ width: "100%" }}>
                {orgSyncPickerReadsBlocked ? (
                  <Alert
                    type="warning"
                    showIcon
                    message="Feishu-backed picker reads are currently blocked"
                    description={orgRuntimeStatus?.blocking_reason || "Run a successful Org Sync to refresh the trusted snapshot before browsing departments or searching employees."}
                  />
                ) : null}
                <Table<Department>
                  rowKey={(record) => record.lark_department_id || String(record.id)}
                  columns={orgDepartmentColumns}
                  dataSource={orgDepartments}
                  loading={orgSyncLoading}
                  pagination={{ pageSize: 10, showSizeChanger: true }}
                  expandable={orgSyncPickerReadsBlocked ? undefined : {
                    onExpand: async (expanded, record) => {
                      if (!expanded) return;
                      const deptId = record.lark_department_id;
                      if (!deptId) return;
                      if (deptEmployees[deptId]) return;
                      setDeptEmployeesLoading(deptId);
                      try {
                        const emps = await fetchEmployeesByDepartment(deptId);
                        setDeptEmployees((prev) => ({ ...prev, [deptId]: emps ?? [] }));
                      } catch (err) {
                        message.error(extractErrorMessage(err) ?? "Failed to load employees");
                      } finally {
                        setDeptEmployeesLoading((current) => (current === deptId ? null : current));
                      }
                    },
                    expandedRowRender: (record) => {
                      const deptId = record.lark_department_id;
                      if (!deptId) return <Text type="secondary">Missing department id</Text>;
                      if (deptEmployeesLoading === deptId) return <Text type="secondary">Loading employees…</Text>;
                      const employees = deptEmployees[deptId] ?? [];
                      if (!employees.length) return <Text type="secondary">No employees found for this department.</Text>;
                      return (
                        <List
                          size="small"
                          dataSource={employees}
                          renderItem={(emp) => (
                            <List.Item>
                              <Space direction="vertical" size={0}>
                                <Text strong>{emp.name || emp.email || emp.lark_user_id}</Text>
                                <Text type="secondary">
                                  {emp.email || "—"} • {emp.department_name || (emp.department_names?.length ? emp.department_names.join(", ") : emp.department_id || "—")} • {emp.job_title || "—"} • {emp.status}
                                </Text>
                              </Space>
                            </List.Item>
                          )}
                        />
                      );
                    },
                  }}
                />

                <div>
                  <Text strong>Employee Search</Text>
                  <Divider style={{ margin: "8px 0 12px" }} />
                  <Input.Search
                    allowClear
                    placeholder="Search by name or email"
                    onSearch={handleEmployeeSearch}
                    loading={employeeSearchLoading}
                    disabled={orgSyncPickerReadsBlocked}
                  />
                  <div style={{ marginTop: 12 }}>
                    {employeeSearchResults.length ? (
                      <List
                        size="small"
                        dataSource={employeeSearchResults}
                        renderItem={(emp) => (
                          <List.Item>
                            <Space direction="vertical" size={0}>
                              <Text strong>{emp.name || emp.email || emp.lark_user_id}</Text>
                              <Text type="secondary">
                                {emp.email || "—"} • Dept: {emp.department_name || (emp.department_names?.length ? emp.department_names.join(", ") : emp.department_id || "—")} • {emp.job_title || "—"} • {emp.status}
                              </Text>
                            </Space>
                          </List.Item>
                        )}
                      />
                    ) : orgSyncPickerReadsBlocked ? (
                      <Text type="secondary">Picker reads are blocked until a fresh Org Sync succeeds.</Text>
                    ) : (
                      <Text type="secondary">Search results appear here.</Text>
                    )}
                  </div>
                </div>
              </Space>
            )}
          </Card>
        </Space>
      ),
    },
    {
      key: "health",
      label: renderTabLabel("System Health", false),
      children: <HealthTab health={health} version={versionInfo} onRefresh={handleRefresh} />,
    },
  ];

  return (
    <Space direction="vertical" size={24} style={{ width: "100%" }}>
      <div>
        <Title level={3}>Platform Settings</Title>
        <Paragraph type="secondary">
          Configure authentication, data lifecycle, and synchronization policies for the Security Center workspace. Changes are fully audited—capture a note for each save to provide context.
        </Paragraph>
        <Space size="middle" wrap>
          <Tag color="blue">{versionTag}</Tag>
          {settings?.checksum ? <Tag color="purple">checksum {settings.checksum.slice(0, 8)}</Tag> : null}
          <Tag color={healthTagColor}>{(health?.status ?? "unknown").toUpperCase()}</Tag>
          <Text type="secondary">Last updated {lastUpdated}{settings?.updated_by?.id ? ` · Actor #${settings.updated_by.id}` : ""}</Text>
          <Link href="/dashboard/logs/audit?resource_type=system_settings" style={{ display: "inline-flex" }}>
            <Button icon={<HistoryOutlined />}>View Audit Trail</Button>
          </Link>
          <Button icon={<ReloadOutlined />} onClick={handleRefresh} disabled={loading}>
            Refresh
          </Button>
        </Space>
      </div>

      {error && (
        <Alert
          type="error"
          message="Unable to load settings"
          description={error}
          action={
            <Button size="small" onClick={handleRefresh}>
              Retry
            </Button>
          }
        />
      )}

      {hasConflict && (
        <Alert
          type="warning"
          message="Settings changed elsewhere"
          description="Reload to pick up the most recent version before applying your updates."
          action={
            <Button type="primary" size="small" onClick={handleRefresh}>
              Reload
            </Button>
          }
        />
      )}

      {!canEdit && (
        <Alert
          type="info"
          showIcon
          message="Read-only access"
          description="You do not have permission to edit system settings. Contact an administrator if you need access."
        />
      )}

      {loading || !settings ? (
        <Card loading style={{ minHeight: 320 }} />
      ) : (
        <Tabs activeKey={activeTab} items={tabItems} onChange={handleTabChange} />
      )}

      <Drawer
        open={deliveriesDrawerOpen}
        onClose={() => setDeliveriesDrawerOpen(false)}
        width={820}
        title={selectedRun ? `Deliveries · Run #${selectedRun.id}` : "Deliveries"}
      >
        <Table<LarkAlertDelivery>
          size="small"
          rowKey="id"
          loading={runDeliveriesLoading}
          dataSource={runDeliveries}
          pagination={{ pageSize: 12 }}
          columns={[
            {
              title: "Status",
              dataIndex: "status",
              key: "status",
              width: 110,
              render: (v: LarkAlertDelivery["status"]) => (
                <Tag color={v === "success" ? "green" : "red"}>{v.toUpperCase()}</Tag>
              ),
            },
            { title: "Type", dataIndex: "recipient_type", key: "recipient_type", width: 110 },
            { title: "Label", dataIndex: "recipient_label", key: "recipient_label", width: 180, render: (v) => v || "—" },
            { title: "Employee", dataIndex: "employee_id", key: "employee_id", width: 110, render: (v) => v ?? "—" },
            { title: "Webhook Hash", dataIndex: "webhook_url_hash", key: "webhook_url_hash", width: 150, render: (v) => (v ? `${v.slice(0, 8)}…` : "—") },
            { title: "Sent At", dataIndex: "sent_at", key: "sent_at", width: 200 },
            { title: "Response", dataIndex: "response_code", key: "response_code", width: 100, render: (v) => v ?? "—" },
            { title: "Error", dataIndex: "error_message", key: "error_message", render: (v) => v || "—" },
          ]}
        />
      </Drawer>

      <Modal
        open={alertRuleModalOpen}
        title={alertEditingRule ? "Edit Lark Alert Rule" : "New Lark Alert Rule"}
        onCancel={() => {
          setAlertRuleModalOpen(false);
          setAlertEditingRule(null);
        }}
        onOk={handleSaveAlertRule}
        okText="Save"
        width={920}
      >
        <Form layout="vertical" form={alertRuleForm} disabled={!canEdit}>
          <Row gutter={12}>
            <Col xs={24} md={16}>
              <Form.Item name="name" label="Rule Name" rules={[{ required: true, message: "Rule name is required" }]}>
                <Input placeholder="High severity vulns to oncall" />
              </Form.Item>
            </Col>
            <Col xs={24} md={8}>
              <Form.Item name="enabled" label="Enabled" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={12}>
            <Col xs={24} md={8}>
              <Form.Item
                name="entity_type"
                label="Entity Type"
                rules={[{ required: true, message: "Entity type is required" }]}
              >
                <Select
                  options={[
                    { value: "vulnerability", label: "vulnerability" },
                    { value: "asset", label: "asset" },
                  ]}
                  onChange={handleRuleEntityChange}
                />
              </Form.Item>
            </Col>
            <Col xs={24} md={8}>
              <Form.Item name="max_matches_per_run" label="Max Matches Per Run">
                <InputNumber min={1} max={200} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col xs={24} md={8}>
              <Form.Item name="cron_expr" label="Cron (optional)">
                <Input placeholder="0 */6 * * *" />
              </Form.Item>
            </Col>
          </Row>

          <Divider style={{ margin: "16px 0" }}>Automatic Triggers</Divider>
          <Space wrap>
            <Form.Item name="event_on_create" label="On Create" valuePropName="checked" style={{ marginBottom: 0 }}>
              <Switch />
            </Form.Item>
            <Form.Item name="event_on_update" label="On Update" valuePropName="checked" style={{ marginBottom: 0 }}>
              <Switch />
            </Form.Item>
            <Form.Item name="event_on_status_change" label="On Status Change" valuePropName="checked" style={{ marginBottom: 0 }}>
              <Switch />
            </Form.Item>
            <Form.Item name="event_on_severity_change" label="On Severity Change" valuePropName="checked" style={{ marginBottom: 0 }}>
              <Switch />
            </Form.Item>
          </Space>

          <Divider style={{ margin: "16px 0" }}>Recipients</Divider>
          <Space wrap>
            <Form.Item name="send_via_webhook" label="Send via Webhook" valuePropName="checked" style={{ marginBottom: 0 }}>
              <Switch />
            </Form.Item>
            <Form.Item name="send_via_app" label="Send via App (employees)" valuePropName="checked" style={{ marginBottom: 0 }}>
              <Switch />
            </Form.Item>
          </Space>
          <Form.Item
            name="recipient_employee_ids"
            label="Employees"
            tooltip="Explicit employee recipients for app-based alerts. Org-aware fan-out remains separate so stale org-sync data cannot silently broaden who receives notifications."
          >
            <Select
              mode="multiple"
              showSearch
              filterOption={false}
              onSearch={handleSearchAlertRecipients}
              loading={alertRecipientSearchLoading}
              options={alertRecipientOptions.map((emp) => ({
                value: emp.id,
                label: `${emp.name}${emp.email ? ` (${emp.email})` : ""}`,
              }))}
              placeholder="Search employees..."
            />
          </Form.Item>
          <Form.Item
            name="recipient_target_keys"
            label="Org-aware routing targets"
            tooltip="Use synced Feishu org data for fan-out. Team and department targets are automatically degraded when Org Sync freshness is stale or expired."
          >
            <Select
              mode="multiple"
              options={[
                { value: "security_team", label: "Security team (fan-out from org data)" },
                { value: "rd_team", label: "R&D team (fan-out from org data)" },
                { value: "entity_department", label: "Entity department (fan-out from the matched record)" },
                { value: "entity_owner", label: "Matched record owner (resolved from employee_id)" },
                { value: "entity_fixer", label: "Matched record fixer (resolved from employee_id)" },
                { value: "entity_submitter", label: "Matched record submitter (resolved from user.employee_id)" },
              ]}
              placeholder="Select org-aware routing targets"
            />
          </Form.Item>

          <Divider style={{ margin: "16px 0" }}>Rule Filters</Divider>
          <Text type="secondary" style={{ display: "block", marginBottom: 8 }}>
            Fields come from the underlying table columns for the selected entity.
          </Text>

          <Form.List name="conditions">
            {(fields, { add, remove }) => (
              <Space direction="vertical" size={8} style={{ width: "100%" }}>
                {fields.map((field) => (
                  <Row key={field.key} gutter={8} align="middle" wrap={false}>
                    <Col flex="260px">
                      <Form.Item
                        {...field}
                        name={[field.name, "field"]}
                        rules={[{ required: true, message: "Field required" }]}
                        style={{ marginBottom: 0 }}
                      >
                        <Select
                          loading={alertFieldsLoading}
                          showSearch
                          options={alertFields.map((f) => ({
                            value: f.name,
                            label: `${f.name} (${f.type})`,
                          }))}
                          placeholder="field"
                        />
                      </Form.Item>
                    </Col>
                    <Col flex="170px">
                      <Form.Item
                        {...field}
                        name={[field.name, "op"]}
                        rules={[{ required: true, message: "Operator required" }]}
                        style={{ marginBottom: 0 }}
                      >
                        <Select
                          options={[
                            { value: "eq", label: "eq" },
                            { value: "neq", label: "neq" },
                            { value: "contains", label: "contains" },
                            { value: "gt", label: "gt" },
                            { value: "gte", label: "gte" },
                            { value: "lt", label: "lt" },
                            { value: "lte", label: "lte" },
                            { value: "in", label: "in (comma-separated)" },
                            { value: "not_in", label: "not_in (comma-separated)" },
                            { value: "is_null", label: "is_null" },
                            { value: "not_null", label: "not_null" },
                          ]}
                        />
                      </Form.Item>
                    </Col>
                    <Col flex="auto">
                      <Form.Item {...field} name={[field.name, "value"]} style={{ marginBottom: 0 }}>
                        <Input placeholder="value" />
                      </Form.Item>
                    </Col>
                    <Col flex="40px">
                      <Button
                        danger
                        type="text"
                        icon={<DeleteOutlined />}
                        aria-label="Remove condition"
                        onClick={() => remove(field.name)}
                      />
                    </Col>
                  </Row>
                ))}
                <Button type="dashed" icon={<PlusOutlined />} onClick={() => add({ op: "eq" })} block>
                  Add Condition
                </Button>
              </Space>
            )}
          </Form.List>

          <Divider style={{ margin: "16px 0" }}>Interactive Card Template (JSON)</Divider>
          <Text type="secondary" style={{ display: "block", marginBottom: 8 }}>
            Go template context: <Text code>.entity</Text> (entity fields), <Text code>.entity_type</Text>.
          </Text>
          <Form.Item name="card_template" rules={[{ required: true, message: "Card template is required" }]}>
            <Input.TextArea rows={10} style={{ fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace" }} />
          </Form.Item>

          <Row gutter={12} align="bottom">
            <Col xs={24} md={10}>
              <Form.Item name="preview_entity_id" label="Preview with Entity ID (optional)" style={{ marginBottom: 0 }}>
                <InputNumber min={1} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col xs={24} md={14}>
              <Button type="dashed" onClick={handlePreviewTemplate} block>
                Validate & Preview Template
              </Button>
            </Col>
          </Row>
        </Form>
      </Modal>

      <Modal
        open={templatePreviewOpen}
        title="Rendered Card Preview"
        onCancel={() => setTemplatePreviewOpen(false)}
        footer={<Button onClick={() => setTemplatePreviewOpen(false)}>Close</Button>}
        width={920}
      >
        <pre style={{ maxHeight: 520, overflow: "auto", background: "#0b1020", color: "#d6deeb", padding: 12, borderRadius: 8 }}>
          {JSON.stringify(templatePreview, null, 2)}
        </pre>
      </Modal>

      <Modal
        open={testSendModalOpen}
        title="Test Lark Alert Send"
        onCancel={() => setTestSendModalOpen(false)}
        onOk={handleTestSend}
        okText="Send"
        width={820}
      >
        <Form layout="vertical" form={testSendForm} disabled={!canEdit}>
          <Alert
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
            message="Test send stays on the explicit recipient path"
            description="This modal verifies direct employee or webhook delivery only. Org-aware fan-out targets such as security team, R&D, or entity department are exercised through saved alert rules so degraded org-sync state remains visible and reviewable."
          />
          <Form.Item name="send_webhook" label="Send via Webhook" valuePropName="checked">
            <Switch />
          </Form.Item>
          <Form.Item name="employee_id" label="Send to Employee (optional)">
            <Select
              showSearch
              allowClear
              filterOption={false}
              onSearch={handleSearchAlertRecipients}
              loading={alertRecipientSearchLoading}
              options={alertRecipientOptions.map((emp) => ({
                value: emp.id,
                label: `${emp.name}${emp.email ? ` (${emp.email})` : ""}`,
              }))}
              placeholder="Search employees..."
            />
          </Form.Item>
          <Form.Item name="card_template" label="Interactive Card Template (JSON)" rules={[{ required: true, message: "Template required" }]}>
            <Input.TextArea rows={10} style={{ fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace" }} />
          </Form.Item>
        </Form>
      </Modal>
    </Space>
  );
}

type HealthTabProps = {
  health: SystemHealth | null;
  version: SystemVersion | null;
  onRefresh: () => void;
};

function HealthTab({ health, version, onRefresh }: HealthTabProps) {
  if (!health) {
    return (
      <Card>
        <Space direction="vertical">
          <Text type="secondary">Health telemetry is currently unavailable.</Text>
          <Button onClick={onRefresh}>Retry</Button>
        </Space>
      </Card>
    );
  }

  return (
    <Space direction="vertical" size={16} style={{ width: "100%" }}>
      <Card title="Uptime & Overview">
        <Descriptions column={1} colon>
          <Descriptions.Item label="Overall Status">
            <Tag color={getStatusColor(health.status)}>{health.status.toUpperCase()}</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="Uptime">{formatDuration(health.uptime_seconds)}</Descriptions.Item>
          <Descriptions.Item label="Last Checked">{formatTimestamp(health.checked_at)}</Descriptions.Item>
          <Descriptions.Item label="Runtime Version">{health.version}</Descriptions.Item>
          {version ? (
            <>
              <Descriptions.Item label="Service">{version.service}</Descriptions.Item>
              <Descriptions.Item label="Release">{version.version}</Descriptions.Item>
              {version.commit ? <Descriptions.Item label="Commit">{version.commit}</Descriptions.Item> : null}
              {version.build_time ? <Descriptions.Item label="Built At">{version.build_time}</Descriptions.Item> : null}
            </>
          ) : null}
        </Descriptions>
      </Card>
      <Card title="Dependency Status">
        <List
          dataSource={health.components}
          renderItem={(component) => (
            <List.Item>
              <Space direction="vertical" size={4} style={{ width: "100%" }}>
                <Text strong>{formatComponentName(component.name)}</Text>
                <Space size="middle">
                  <Tag color={getStatusColor(component.status)}>{component.status.toUpperCase()}</Tag>
                  {component.latency_ms ? <Text type="secondary">{component.latency_ms} ms</Text> : null}
                </Space>
                {component.error ? <Text type="danger">{component.error}</Text> : null}
                <Text type="secondary">Checked at {formatTimestamp(component.checked_at)}</Text>
              </Space>
            </List.Item>
          )}
        />
      </Card>
    </Space>
  );
}

function extractErrorMessage(error: unknown): string | null {
  if (!error) return null;
  if (typeof error === "string") return error;
  if (error instanceof Error) {
    const anyErr = error as Error & { response?: { data?: { message?: string } } };
    return anyErr.response?.data?.message ?? error.message ?? null;
  }
  if (typeof error === "object" && "response" in (error as Record<string, unknown>)) {
    const response = (error as { response?: { data?: { message?: string } } }).response;
    return response?.data?.message ?? null;
  }
  return null;
}

function isOrgSyncPickerReadsBlockedError(error: unknown): boolean {
  const message = extractErrorMessage(error);
  return Boolean(message?.toLowerCase().includes("org sync snapshot is expired"));
}

function getStatusColor(status: string) {
  switch (status?.toLowerCase()) {
    case "ok":
      return "green";
    case "degraded":
      return "orange";
    case "down":
      return "red";
    default:
      return "default";
  }
}

function formatTimestamp(unixSeconds: number) {
  if (!unixSeconds) return "n/a";
  const date = new Date(unixSeconds * 1000);
  if (Number.isNaN(date.getTime())) return "n/a";
  return date.toLocaleString();
}

function formatDuration(seconds: number) {
  if (!seconds) return "0s";
  const hrs = Math.floor(seconds / 3600);
  const mins = Math.floor((seconds % 3600) / 60);
  const secs = Math.floor(seconds % 60);
  if (hrs > 0) {
    return `${hrs}h ${mins}m`;
  }
  if (mins > 0) {
    return `${mins}m ${secs}s`;
  }
  return `${secs}s`;
}

function formatComponentName(name: string) {
  if (!name) return "Unknown";
  return name
    .split("_")
    .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
    .join(" ");
}

type DiffEntry = {
  field: string;
  before: string;
  after: string;
};

function sanitizeSensitiveSettings<T extends Record<string, unknown>>(
  snapshot: T | undefined,
  fields: string[],
): T | undefined {
  if (!snapshot) return snapshot;
  const clone: Record<string, unknown> = { ...snapshot };
  for (const field of fields) {
    if (field in clone) {
      clone[field] = "";
    }
  }
  return clone as T;
}

function pickComparableFields<T extends Record<string, unknown>, K extends readonly string[]>(
  snapshot: T | undefined,
  fields: K,
): Partial<T> | undefined {
  if (!snapshot) {
    return undefined;
  }
  const picked: Partial<T> = {};
  fields.forEach((field) => {
    (picked as Record<string, unknown>)[field] = (snapshot as Record<string, unknown>)[field];
  });
  return picked;
}

function computeDiff<T extends Record<string, unknown>>(
  baseline?: Partial<T> | null,
  current?: Partial<T> | null,
  exclude: string[] = [],
): DiffEntry[] {
  if (!baseline || !current) {
    return [];
  }
  const skip = new Set(exclude ?? []);
  const keys = new Set([...Object.keys(baseline), ...Object.keys(current)]);
  const entries: DiffEntry[] = [];
  keys.forEach((key) => {
    if (skip.has(key)) {
      return;
    }
    const before = (baseline as Record<string, unknown>)[key];
    const after = (current as Record<string, unknown>)[key];
    const normalizedBefore = normalizeComparableValue(before);
    const normalizedAfter = normalizeComparableValue(after);
    if (isEqualValue(normalizedBefore, normalizedAfter)) {
      return;
    }
    entries.push({
      field: key,
      before: formatValue(key, before),
      after: formatValue(key, after),
    });
  });
  return entries;
}

function normalizeComparableValue(value: unknown): unknown {
  if (value === null || value === undefined || value === "") {
    return undefined;
  }

  if (Array.isArray(value)) {
    const normalized = value
      .map((item) => normalizeComparableValue(item))
      .filter((item): item is unknown => item !== undefined);
    return normalized.length ? normalized : undefined;
  }

  if (isPlainObject(value)) {
    const normalizedEntries = Object.entries(value)
      .map(([key, nested]) => [key, normalizeComparableValue(nested)] as const)
      .filter(([, nested]) => nested !== undefined);
    return normalizedEntries.length ? Object.fromEntries(normalizedEntries) : undefined;
  }

  return value;
}

function isPlainObject(value: unknown): value is Record<string, unknown> {
  return Boolean(value) && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype;
}

function isEqualValue(a: unknown, b: unknown) {
  if (a === b) return true;
  try {
    return JSON.stringify(a) === JSON.stringify(b);
  } catch {
    return false;
  }
}

function formatValue(field: string, value: unknown) {
  const lowerField = field.toLowerCase();
  if (lowerField.includes("secret") || lowerField.includes("token") || lowerField.includes("webhook")) {
    return "••••••••";
  }
  if (value === null || value === undefined || value === "") return "—";
  if (typeof value === "boolean") return value ? "Enabled" : "Disabled";
  if (typeof value === "object") {
    return JSON.stringify(value);
  }
  return String(value);
}

function ChangeList({ entries }: { entries: DiffEntry[] }) {
  if (!entries.length) {
    return null;
  }
  return (
    <ul style={{ paddingLeft: 20, margin: 0 }}>
      {entries.map((entry) => (
        <li key={entry.field}>
          <Text strong>{formatLabel(entry.field)}:</Text> {entry.before} → {entry.after}
        </li>
      ))}
    </ul>
  );
}

function formatLabel(field: string) {
  return field
    .replace(/_/g, " ")
    .replace(/([a-z])([A-Z])/g, "$1 $2")
    .replace(/\b\w/g, (char) => char.toUpperCase());
}

function renderTabLabel(text: string, dirty: boolean, saving?: boolean, savedAt?: string | null) {
  const statusTag = saving ? (
    <Tag color="blue">Saving</Tag>
  ) : dirty ? (
    <Tag color="orange">Unsaved</Tag>
  ) : savedAt ? (
    <Tag color="green">Saved</Tag>
  ) : null;
  return (
    <Space size={4}>
      <span>{text}</span>
      {statusTag}
    </Space>
  );
}

type MaskedFieldProps = {
  name: string;
  label: string;
  placeholder?: string;
  onReveal?: (field: string) => void;
  required?: boolean;
  configured?: boolean;
};

function MaskedSecretField({ name, label, placeholder, onReveal, required, configured }: MaskedFieldProps) {
  const [revealed, setRevealed] = useState(false);
  const isConfigured = configured ?? false;
  const handleReveal = () => {
    setRevealed(true);
    onReveal?.(name);
  };

  // Only require field if:
  // 1. The field is marked as required, AND
  // 2. The secret is NOT already configured (if configured, backend will preserve it)
  const shouldRequire = required && !isConfigured;

  return (
    <>
      <Form.Item
        label={label}
        name={name}
        rules={
          required && !isConfigured
            ? [
                {
                  validator: async (_, value) => {
                    // If already configured, no validation needed (backend preserves it)
                    if (isConfigured) {
                      return Promise.resolve();
                    }

                    // If required and not configured, must have a value
                    if (required && !value?.trim()) {
                      return Promise.reject(new Error(`${label} is required`));
                    }

                    return Promise.resolve();
                  },
                },
              ]
            : undefined
        }
      >
        <Input
          placeholder={
            revealed
              ? placeholder
              : isConfigured
                ? "Configured (hidden)"
                : (placeholder ?? "Not set")
          }
          type={revealed ? "text" : "password"}
          readOnly={isConfigured && !revealed}
          autoComplete="off"
          suffix={
            isConfigured ? (
              revealed ? (
              <Button type="link" size="small" icon={<EyeInvisibleOutlined />} onClick={() => setRevealed(false)}>
                Hide
              </Button>
            ) : (
              <Popconfirm
                title="Reveal secret?"
                description="Confirm to reveal and edit this sensitive value."
                okText="Reveal"
                cancelText="Cancel"
                icon={<WarningOutlined />}
                onConfirm={handleReveal}
              >
                <Button type="link" size="small" icon={<EyeOutlined />}>
                  Reveal
                </Button>
              </Popconfirm>
            ))
            : undefined
          }
        />
      </Form.Item>
      <Text type="secondary" style={{ display: "block", marginTop: -16, marginBottom: 16 }}>
        {isConfigured
          ? (revealed ? "Value visible. Enter the full secret to rotate it, or leave blank and save to keep existing." : "Configured. Reveal requires confirmation.")
          : "Not set. Enter a value and save to configure."}
      </Text>
    </>
  );
}

function handleSensitiveReveal(field: string) {
  message.info(`Sensitive field "${formatLabel(field)}" unlocked for editing.`);
}
