'use client';

import React, { useEffect, useState, useCallback, useMemo } from 'react';
import {
  Alert, Card, Form, Input, Button, InputNumber, message, Tabs, Space, Table,
  Tag, Switch, Select, Collapse, Row, Col, Tooltip, Modal, Divider, Descriptions, Typography
} from 'antd';
import {
  MinusCircleOutlined, PlusOutlined, InfoCircleOutlined,
  DeleteOutlined, EditOutlined, SaveOutlined, PlayCircleOutlined, StopOutlined, PauseCircleOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import {
  fetchCaasmConfig,
  fetchSchedulerStatus,
  fetchRuntimeStatus,
  startWorkers,
  stopWorkers,
  startScheduler,
  stopScheduler,
  enableRuntimeKillSwitch,
  disableRuntimeKillSwitch,
  updateCaasmConfig,
  updateCaasmTaggingRules,
  updateCaasmPortCatalog,
  updateCaasmEphemeralPolicy,
  updateCaasmSyncSettings,
} from '@/lib/api/caasm';
import { Badge, Statistic } from 'antd';
import { ClockCircleOutlined, SyncOutlined } from '@ant-design/icons';
import type { SchedulerStatus } from '@/types/models';
import type {
  CaasmConfig, TaggingRule, RiskPortDefinition, Condition,
  EphemeralAssetPolicy, PortCatalog, RuntimeStatus, CaasmConfigEnvelope, EffectiveThrottling, ThrottlingContract, ThrottlingPresetEntry
} from '@/types/models';
import CloudAccountsClient from '@/app/dashboard/caasm/cloud-accounts/cloud-accounts-client';

const { TabPane } = Tabs;
const { Option } = Select;
const { Panel } = Collapse;
const { Paragraph } = Typography;

function LabelWithHelp({ label, help }: { label: string; help: React.ReactNode }) {
  return (
    <Space size={6}>
      <span>{label}</span>
      <Tooltip title={help}>
        <InfoCircleOutlined style={{ color: '#64748b', cursor: 'help' }} />
      </Tooltip>
    </Space>
  );
}

function helpWithRecommendation(summary: string, recommendation: string) {
  return (
    <Space direction="vertical" size={2}>
      <span>{summary}</span>
      <span><strong>Recommended:</strong> {recommendation}</span>
    </Space>
  );
}

function EffectiveValue({
  label,
  help,
  value,
}: {
  label: string;
  help: React.ReactNode;
  value: React.ReactNode;
}) {
  return (
    <span>
      <LabelWithHelp label={label} help={help} />: {value}
    </span>
  );
}

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

  if (typeof value === "string") {
    const trimmed = value.trim();
    return trimmed ? trimmed : undefined;
  }

  if (typeof value === "number" || typeof value === "boolean") {
    return value;
  }

  if (Array.isArray(value)) {
    const next = value
      .map((item) => normalizeConfigSnapshot(item))
      .filter((item) => item !== undefined);
    return next.length ? next : undefined;
  }

  if (typeof value === "object") {
    const entries = Object.entries(value as Record<string, unknown>)
      .map(([key, item]) => [key, normalizeConfigSnapshot(item)] as const)
      .filter(([, item]) => item !== undefined)
      .sort(([left], [right]) => left.localeCompare(right));

    return entries.length ? Object.fromEntries(entries) : undefined;
  }

  return value;
}

function fingerprintConfig(value: unknown): string {
  const normalized = normalizeConfigSnapshot(value);
  return JSON.stringify(normalized ?? {});
}

function formatLastSaved(value: string | null): string {
  if (!value) {
    return "No saves yet";
  }

  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    return value;
  }

  return date.toLocaleString();
}

const DEFAULT_EPHEMERAL_POLICY = {
  ttl_hours: 24,
  enable_auto_cleanup: true,
  preserve_history: true,
  cleanup_cron_schedule: '0 */6 * * *',
};

const DEFAULT_DISCOVERY_INTERVALS = {
  aws: 60,
  gcp: 120,
  azure: 120,
};

const DEFAULT_COLLECTION_SCOPE = {
  ip_collection_scope: 'all',
  port_collection_scope: 'all',
  domain_collection_scope: 'all',
} as const;

const DEFAULT_SYNC_SETTINGS = {
  mode: 'serverless',
  lambda_function_name: 'caasm-collector',
  execution_timeout_minutes: 30,
  running_timeout_minutes: 60,
  queued_timeout_minutes: 30,
} as const;

const DEFAULT_THROTTLING = {
  enabled: true,
  token_capacity: 20,
  token_refill_per_sec: 10,
  adaptive_threshold: 3,
  adaptive_window_sec: 60,
  cool_off_sec: 30,
  max_concurrency: 5,
  min_concurrency: 2,
  circuit_breaker: {
    threshold: 6,
    cool_off_sec: 60,
  },
  service_limits: {},
};

function mergeThrottlingConfig(...sources: Array<Partial<ThrottlingContract["defaults"]> | undefined>) {
  const merged: NonNullable<CaasmConfig["throttling"]> = {
    ...DEFAULT_THROTTLING,
    circuit_breaker: { ...DEFAULT_THROTTLING.circuit_breaker },
    service_limits: { ...DEFAULT_THROTTLING.service_limits },
  };

  sources.forEach((source) => {
    if (!source) {
      return;
    }
    Object.assign(merged, source);
    if (source.circuit_breaker) {
      merged.circuit_breaker = {
        ...merged.circuit_breaker,
        ...source.circuit_breaker,
      };
    }
    if (source.service_limits) {
      merged.service_limits = Object.fromEntries(
        Object.entries(source.service_limits).map(([key, value]) => [
          key,
          { ...(value || {}) },
        ]),
      );
    }
  });

  return merged;
}



const RISK_LEVELS = [
  { value: 'critical', label: 'Critical', color: 'red' },
  { value: 'high', label: 'High', color: 'orange' },
  { value: 'medium', label: 'Medium', color: 'gold' },
  { value: 'low', label: 'Low', color: 'blue' },
];

const OPERATORS = [
  { value: 'equals', label: 'Equals' },
  { value: 'in', label: 'In list' },
  { value: 'contains', label: 'Contains' },
  { value: 'regex', label: 'Regex match' },
  { value: 'exists', label: 'Exists' },
  { value: 'greater_than', label: 'Greater than' },
  { value: 'less_than', label: 'Less than' },
];

const ASSET_FIELDS = [
  { value: 'environment', label: 'Environment' },
  { value: 'source_service', label: 'Source Service' },
  { value: 'public_exposure', label: 'Public Exposure' },
  { value: 'status', label: 'Status' },
  { value: 'asset_type', label: 'Asset Type' },
  { value: 'name', label: 'Name' },
];

function SchedulerStatusCard() {
  const [status, setStatus] = useState<SchedulerStatus | undefined>(undefined);
  const [runtimeStatus, setRuntimeStatus] = useState<RuntimeStatus | undefined>(undefined);
  const [loading, setLoading] = useState(false);

  const loadStatus = async () => {
    setLoading(true);
    try {
      const [data, runtime] = await Promise.all([
        fetchSchedulerStatus(),
        fetchRuntimeStatus().catch(() => undefined),
      ]);
      setStatus(data);
      setRuntimeStatus(runtime);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadStatus();
    // Refresh every 30 seconds
    const interval = setInterval(loadStatus, 30000);
    return () => clearInterval(interval);
  }, []);

  if (!status) return null;
  const schedulerRunning = runtimeStatus?.scheduler_running ?? status.is_running;

  return (
    <Card
      title={
        <Space>
          <ClockCircleOutlined />
          <span>Scheduler Status</span>
        </Space>
      }
      extra={
        <Button
          type="text"
          icon={<SyncOutlined spin={loading} />}
          onClick={loadStatus}
        />
      }
      size="small"
      className="bg-gray-50"
    >
      <Row gutter={16}>
        <Col span={8}>
          <Statistic
            title="State"
            value={schedulerRunning ? "Running" : "Stopped"}
            valueStyle={{ color: schedulerRunning ? '#3f8600' : '#cf1322', fontSize: '16px', fontWeight: 600 }}
            prefix={<Badge status={schedulerRunning ? "success" : "error"} />}
          />
        </Col>
        <Col span={8}>
          <Statistic
            title="Last Run"
            value={status.last_run_at ? new Date(status.last_run_at).toLocaleTimeString() : 'Never'}
            valueStyle={{ fontSize: '16px' }}
          />
        </Col>
        <Col span={8}>
          <Statistic
            title="Next Run (Approx)"
            value={status.next_run_at ? new Date(status.next_run_at).toLocaleTimeString() : '-'}
            valueStyle={{ fontSize: '16px' }}
          />
        </Col>
      </Row>
    </Card>
  );
}

function RuntimeControlCard() {
  const [status, setStatus] = useState<RuntimeStatus | undefined>(undefined);
  const [loading, setLoading] = useState(false);
  const [action, setAction] = useState<
    'start-workers' | 'stop-workers' | 'start-scheduler' | 'stop-scheduler' | 'enable-kill-switch' | 'disable-kill-switch' | null
  >(null);

  const loadStatus = useCallback(async () => {
    setLoading(true);
    try {
      const data = await fetchRuntimeStatus();
      setStatus(data);
    } catch (err: any) {
      message.error(err?.response?.data?.message || 'Failed to load runtime status');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadStatus();
  }, [loadStatus]);

  const handleStartWorkers = async () => {
    setAction('start-workers');
    try {
      const data = await startWorkers();
      setStatus(data);
      message.success('Started CAASM worker pool');
    } catch (err: any) {
      message.error(err?.response?.data?.message || 'Failed to start worker pool');
    } finally {
      setAction(null);
    }
  };

  const handleStopWorkers = async () => {
    setAction('stop-workers');
    try {
      const data = await stopWorkers();
      setStatus(data);
      message.success('Stopped CAASM worker pool');
    } catch (err: any) {
      message.error(err?.response?.data?.message || 'Failed to stop worker pool');
    } finally {
      setAction(null);
    }
  };

  const handleStartScheduler = async () => {
    setAction('start-scheduler');
    try {
      const data = await startScheduler();
      setStatus(data);
      message.success('Started CAASM scheduler');
    } catch (err: any) {
      message.error(err?.response?.data?.message || 'Failed to start scheduler');
    } finally {
      setAction(null);
    }
  };

  const handleStopScheduler = async () => {
    setAction('stop-scheduler');
    try {
      const data = await stopScheduler();
      setStatus(data);
      message.success('Stopped CAASM scheduler');
    } catch (err: any) {
      message.error(err?.response?.data?.message || 'Failed to stop scheduler');
    } finally {
      setAction(null);
    }
  };

  const handleEnableKillSwitch = async () => {
    setAction('enable-kill-switch');
    try {
      const data = await enableRuntimeKillSwitch();
      setStatus(data);
      message.success('Emergency stop enabled');
    } catch (err: any) {
      message.error(err?.response?.data?.message || 'Failed to enable emergency stop');
    } finally {
      setAction(null);
    }
  };

  const handleDisableKillSwitch = async () => {
    setAction('disable-kill-switch');
    try {
      const data = await disableRuntimeKillSwitch();
      setStatus(data);
      message.success('Emergency stop disabled');
    } catch (err: any) {
      message.error(err?.response?.data?.message || 'Failed to disable emergency stop');
    } finally {
      setAction(null);
    }
  };

  return (
    <Card
      title={
        <Space>
          <PlayCircleOutlined />
          <span>Runtime Control</span>
        </Space>
      }
      extra={
        <Button
          type="text"
          icon={<SyncOutlined spin={loading} />}
          onClick={loadStatus}
        />
      }
      size="small"
    >
      <Space direction="vertical" size="small" style={{ width: '100%' }}>
        {status?.kill_switch_enabled && (
          <Alert
            type="error"
            showIcon
            message="Emergency stop enabled"
            description="New syncs are blocked, queue workers stay stopped, and the runtime will not auto-restart until you disable the switch and start it again."
          />
        )}
        {!status?.kill_switch_enabled && status?.runtime_configured && status?.scheduler_running === false && (
          <Alert
            type="info"
            showIcon
            message="Scheduler paused, manual sync still available"
            description="Scheduled sync automation is currently disabled. Manual syncs can still be queued from Cloud Accounts as long as the emergency stop is off."
          />
        )}
        <Space size="large">
          <Space>
            <Badge status={status?.workers_running ? "success" : "error"} />
            <span>Workers: {status?.workers_running ? "Running" : "Stopped"}</span>
          </Space>
          <Space>
            <Badge status={status?.scheduler_running ? "processing" : "warning"} />
            <span>Scheduler: {status?.scheduler_running ? "Running" : "Stopped"}</span>
          </Space>
          <Tag color={status?.kill_switch_enabled ? "red" : "green"}>
            Emergency stop {status?.kill_switch_enabled ? "enabled" : "disabled"}
          </Tag>
        </Space>
        {!status?.runtime_configured && (
          <Tag color="red">Runtime not configured</Tag>
        )}
        {status?.runtime_configured && (
          <Descriptions size="small" column={2} bordered>
            <Descriptions.Item label="Worker limit">{status.worker_limit ?? "-"}</Descriptions.Item>
            <Descriptions.Item label="Runtime pressure cap">{status.runtime_pressure_cap ?? "-"}</Descriptions.Item>
            <Descriptions.Item label="Active jobs">{status.active_job_count ?? 0}</Descriptions.Item>
            <Descriptions.Item label="Pressure state">{status.pressure_state ?? "idle"}</Descriptions.Item>
            <Descriptions.Item label="Coordination">{status.coordination_mode ?? "db_backed"}</Descriptions.Item>
            <Descriptions.Item label="Limit source">{status.runtime_limit_source ?? "global_default"}</Descriptions.Item>
          </Descriptions>
        )}
        <Row gutter={[12, 12]} style={{ marginTop: '12px' }}>
          <Col xs={24} md={8} style={{ display: 'flex' }}>
            <Card
              size="small"
              title="Worker Pool"
              style={{ width: '100%' }}
              styles={{ body: { height: '100%' } }}
            >
              <Space direction="vertical" size="small" style={{ width: '100%', height: '100%' }}>
                <Paragraph type="secondary" style={{ marginBottom: 0 }}>
                  Processes queued sync jobs and manual sync requests. Stopping workers pauses processing only; scheduler automation remains a separate control.
                </Paragraph>
                <Space style={{ marginTop: 'auto' }}>
                  <Button
                    type="primary"
                    icon={<PlayCircleOutlined />}
                    onClick={handleStartWorkers}
                    loading={action === 'start-workers'}
                    disabled={!status?.runtime_configured || status?.kill_switch_enabled || status?.workers_running}
                  >
                    Start Workers
                  </Button>
                  <Button
                    danger
                    icon={<StopOutlined />}
                    onClick={handleStopWorkers}
                    loading={action === 'stop-workers'}
                    disabled={!status?.runtime_configured || !status?.workers_running}
                  >
                    Stop Workers
                  </Button>
                </Space>
              </Space>
            </Card>
          </Col>
          <Col xs={24} md={8} style={{ display: 'flex' }}>
            <Card
              size="small"
              title="Scheduler"
              style={{ width: '100%' }}
              styles={{ body: { height: '100%' } }}
            >
              <Space direction="vertical" size="small" style={{ width: '100%', height: '100%' }}>
                <Paragraph type="secondary" style={{ marginBottom: 0 }}>
                  Controls automatic scheduled syncs. It can stay off while manual sync remains available.
                </Paragraph>
                <Space style={{ marginTop: 'auto' }}>
                  <Button
                    type="primary"
                    icon={<PlayCircleOutlined />}
                    onClick={handleStartScheduler}
                    loading={action === 'start-scheduler'}
                    disabled={!status?.runtime_configured || status?.kill_switch_enabled || status?.scheduler_running}
                  >
                    Start Scheduler
                  </Button>
                  <Button
                    icon={<PauseCircleOutlined />}
                    onClick={handleStopScheduler}
                    loading={action === 'stop-scheduler'}
                    disabled={!status?.runtime_configured || !status?.scheduler_running}
                  >
                    Stop Scheduler
                  </Button>
                </Space>
              </Space>
            </Card>
          </Col>
          <Col xs={24} md={8} style={{ display: 'flex' }}>
            <Card
              size="small"
              title="Emergency Stop"
              style={{ width: '100%' }}
              styles={{ body: { height: '100%' } }}
            >
              <Space direction="vertical" size="small" style={{ width: '100%', height: '100%' }}>
                <Paragraph type="secondary" style={{ marginBottom: 0 }}>
                  Higher-priority hard block. When enabled, both scheduler automation and manual sync are blocked.
                </Paragraph>
                <div style={{ marginTop: 'auto' }}>
                {status?.kill_switch_enabled ? (
                  <Button
                    icon={<PlayCircleOutlined />}
                    onClick={handleDisableKillSwitch}
                    loading={action === 'disable-kill-switch'}
                  >
                    Disable Emergency Stop
                  </Button>
                ) : (
                  <Button
                    danger
                    icon={<PauseCircleOutlined />}
                    onClick={handleEnableKillSwitch}
                    loading={action === 'enable-kill-switch'}
                  >
                    Enable Emergency Stop
                  </Button>
                )}
                </div>
              </Space>
            </Card>
          </Col>
        </Row>
      </Space>
    </Card>
  );
}

export default function ConfigPage() {
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [lastSavedAt, setLastSavedAt] = useState<string | null>(null);
  const [form] = Form.useForm();
  const [selectedThrottlingPresetKey, setSelectedThrottlingPresetKey] = useState<string | undefined>(undefined);
  const [config, setConfig] = useState<CaasmConfig>({});
  const [configEnvelope, setConfigEnvelope] = useState<CaasmConfigEnvelope | null>(null);

  const loadConfig = useCallback(async () => {
    setLoading(true);
    try {
      const envelope = await fetchCaasmConfig();
      const data = envelope.config || {};

      const merged = {
        ...data,
        ephemeral_asset_policy: { ...DEFAULT_EPHEMERAL_POLICY, ...(data?.ephemeral_asset_policy || {}) },
        discovery_intervals: { ...DEFAULT_DISCOVERY_INTERVALS, ...(data?.discovery_intervals || {}) },
        collection_scope: { ...DEFAULT_COLLECTION_SCOPE, ...(data?.collection_scope || {}) },
        sync_settings: { ...DEFAULT_SYNC_SETTINGS, ...(data?.sync_settings || {}) },
        throttling: mergeThrottlingConfig(data?.throttling as Partial<ThrottlingContract["defaults"]> | undefined),
      };
      setConfigEnvelope(envelope);
      setConfig(merged);
      form.setFieldsValue(merged);
    } catch (err) {
      console.error(err);
      message.error('Failed to load configuration');
    } finally {
      setLoading(false);
    }
  }, [form]);

  useEffect(() => {
    loadConfig();
  }, [loadConfig]);

  const formValues = Form.useWatch([], form);
  const buildPayload = () => {
    return buildMergedConfig(form.getFieldsValue(true), config);
  };

  const currentDraft = useMemo(
    () => buildMergedConfig(formValues, config),
    [config, formValues],
  );
  const throttlingPresetEntries = useMemo<ThrottlingPresetEntry[]>(() => {
    const presets = configEnvelope?.throttling_contract?.presets || {};
    return Object.entries(presets)
      .map(([key, preset]) => ({ key, preset }))
      .sort((left, right) => left.preset.label.localeCompare(right.preset.label));
  }, [configEnvelope?.throttling_contract?.presets]);
  const selectedThrottlingPreset = useMemo(
    () => throttlingPresetEntries.find((entry) => entry.key === selectedThrottlingPresetKey),
    [selectedThrottlingPresetKey, throttlingPresetEntries],
  );

  useEffect(() => {
    if (!throttlingPresetEntries.length) {
      setSelectedThrottlingPresetKey(undefined);
      return;
    }
    if (!selectedThrottlingPresetKey || !throttlingPresetEntries.some((entry) => entry.key === selectedThrottlingPresetKey)) {
      setSelectedThrottlingPresetKey(throttlingPresetEntries[0].key);
    }
  }, [selectedThrottlingPresetKey, throttlingPresetEntries]);

  const handleApplyThrottlingPreset = useCallback(() => {
    if (!selectedThrottlingPreset) {
      message.warning('Select a throttling preset first');
      return;
    }
    form.setFieldsValue({
      throttling: mergeThrottlingConfig(selectedThrottlingPreset.preset.config),
    });
    message.success(`Applied preset: ${selectedThrottlingPreset.preset.label}`);
  }, [form, selectedThrottlingPreset]);

  const hasUnsavedChanges = useMemo(
    () => fingerprintConfig(currentDraft) !== fingerprintConfig(config),
    [config, currentDraft],
  );
  const saveStateLabel = loading
    ? "Loading configuration"
    : hasUnsavedChanges
      ? "Unsaved changes"
      : "All changes saved";

  const saveSection = async (
    fields: (string | (string | number)[])[],
    successMessage: string,
    apiCall: (payload: any) => Promise<any>,
    build: () => any,
  ) => {
    setSaving(true);
    try {
      await form.validateFields(fields);
      const payload = build();
      await apiCall(payload);
      message.success(successMessage);
      setLastSavedAt(new Date().toISOString());
      await loadConfig();
    } catch (error: any) {
      if (error?.response?.data?.message) {
        message.error(error.response.data.message);
      } else if (error?.errorFields) {
        message.error(error.errorFields[0]?.errors?.[0] || 'Validation failed');
      } else {
        message.error('Failed to update configuration');
      }
    } finally {
      setSaving(false);
    }
  };

  const onFinish = async (values: any) => {
    setSaving(true);
    try {
      const payload = buildPayload();
      await updateCaasmConfig(payload);
      message.success('Configuration updated successfully');
      setLastSavedAt(new Date().toISOString());
      await loadConfig(); // Reload to get validated data
    } catch (error: any) {
      message.error(error?.response?.data?.message || 'Failed to update configuration');
    } finally {
      setSaving(false);
    }
  };

  // Port Catalog Columns
  const portColumns: ColumnsType<RiskPortDefinition> = [
    {
      title: 'Port',
      dataIndex: 'port',
      key: 'port',
      width: 100,
      sorter: (a, b) => a.port - b.port,
    },
    {
      title: 'Protocol',
      dataIndex: 'protocol',
      key: 'protocol',
      width: 100,
      render: (protocol: string) => <Tag>{protocol.toUpperCase()}</Tag>,
    },
    {
      title: 'Service',
      dataIndex: 'service',
      key: 'service',
      width: 150,
    },
    {
      title: 'Risk Level',
      dataIndex: 'risk_level',
      key: 'risk_level',
      width: 120,
      render: (level: string) => {
        const config = RISK_LEVELS.find(r => r.value === level);
        return <Tag color={config?.color}>{config?.label}</Tag>;
      },
    },
    {
      title: 'Reason',
      dataIndex: 'reason',
      key: 'reason',
      ellipsis: true,
    },
    {
      title: 'Enabled',
      dataIndex: 'enabled',
      key: 'enabled',
      width: 100,
      render: (enabled: boolean) => (
        <Tag color={enabled ? 'green' : 'default'}>{enabled ? 'Yes' : 'No'}</Tag>
      ),
    },
  ];

  return (
    <div className="p-8 max-w-7xl mx-auto">
      <div className="mb-6 pb-6 border-b border-gray-200">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">CAASM Configuration</h1>
          <p className="text-gray-500 mt-2 text-base max-w-3xl">
            Manage automation rules, port classifications, asset lifecycle policies, and discovery settings.
            Review the top-level status cues first, then drill into the tabs for detailed edits.
          </p>
        </div>
      </div>

      {hasUnsavedChanges ? (
        <Alert
          className="mb-6"
          type="warning"
          showIcon
          message="Unsaved configuration edits"
          description="You have changes in one or more tabs. Save before leaving this page or switch tabs only after checking the draft state."
        />
      ) : null}

      <Space direction="vertical" size={16} style={{ width: '100%', marginBottom: 24 }}>
        <RuntimeControlCard />
        <SchedulerStatusCard />
      </Space>

      <Form
        id="caasm-config-form"
        form={form}
        layout="vertical"
        onFinish={onFinish}
        onFinishFailed={({ errorFields }) => {
          if (errorFields?.length) {
            message.error(errorFields[0].errors?.[0] || 'Please fix validation errors');
            // Scroll to the first error (across tabs)
            form.scrollToField(errorFields[0].name);
          }
        }}
        scrollToFirstError
        disabled={loading || saving}
      >
        <Card className="shadow-sm" bordered={false}>
          {lastSavedAt ? (
            <div className="mb-4 flex items-center justify-end gap-2 text-xs text-slate-500">
              <ClockCircleOutlined className="text-slate-400" />
              <span>Last saved {formatLastSaved(lastSavedAt)}</span>
            </div>
          ) : null}
          <Tabs defaultActiveKey="tagging">
            {/* Enhanced Tagging Rules */}
            <TabPane tab="Tagging Rules" key="tagging">
              <div className="max-w-4xl">
                <p className="mb-6 text-gray-600">
                  Define intelligent tagging rules with complex conditions (AND/OR/NOT logic) to automatically classify assets.
                </p>

                <Form.List name={['tagging_rules']}>
                  {(fields, { add, remove }) => (
                    <>
                      {fields.map(({ key, name, ...restField }) => (
                        <Card
                          key={key}
                          size="small"
                          className="mb-4 shadow-sm"
                          title={
                            <Form.Item
                              {...restField}
                              name={[name, 'name']}
                              noStyle
                            >
                              <Input
                                aria-label="Tagging rule name"
                                id={`tagging-rule-name-${name}`}
                                placeholder="Rule Name"
                                className="font-semibold"
                                style={{ border: 'none', fontSize: '16px' }}
                              />
                            </Form.Item>
                          }
                          extra={
                            <Space>
                              <Form.Item
                                {...restField}
                                name={[name, 'enabled']}
                                valuePropName="checked"
                                noStyle
                              >
                                <Switch
                                  aria-label="Enable tagging rule"
                                  id={`tagging-rule-enabled-${name}`}
                                  checkedChildren="Enabled"
                                  unCheckedChildren="Disabled"
                                />
                              </Form.Item>
                              <Button
                                type="text"
                                danger
                                icon={<DeleteOutlined />}
                                aria-label="Delete tagging rule"
                                onClick={() => remove(name)}
                              />
                            </Space>
                          }
                        >
                          {/* ALL OF (AND) Conditions */}
                          <Collapse ghost>
                            <Panel header="ALL OF (AND) - All conditions must match" key="all_of">
                              <Form.List name={[name, 'conditions', 'all_of']}>
                                {(condFields, { add: addCond, remove: removeCond }) => (
                                  <>
                                    {condFields.map(({ key: condKey, name: condName }) => (
                                      <Row key={condKey} gutter={8} className="mb-2">
                                        <Col span={7}>
                                          <Form.Item name={[condName, 'field']} noStyle>
                                            <Select aria-label="Condition field" placeholder="Field" options={ASSET_FIELDS} />
                                          </Form.Item>
                                        </Col>
                                        <Col span={6}>
                                          <Form.Item name={[condName, 'operator']} noStyle>
                                            <Select aria-label="Condition operator" placeholder="Operator" options={OPERATORS} />
                                          </Form.Item>
                                        </Col>
                                        <Col span={9}>
                                          <Form.Item name={[condName, 'value']} noStyle>
                                            <Input aria-label="Condition value" placeholder="Value" />
                                          </Form.Item>
                                        </Col>
                                        <Col span={2}>
                                          <Button
                                            type="text"
                                            danger
                                            icon={<MinusCircleOutlined />}
                                            aria-label="Remove condition"
                                            onClick={() => removeCond(condName)}
                                          />
                                        </Col>
                                      </Row>
                                    ))}
                                    <Button
                                      type="dashed"
                                      onClick={() => addCond()}
                                      block
                                      icon={<PlusOutlined />}
                                      className="mt-2"
                                    >
                                      Add AND Condition
                                    </Button>
                                  </>
                                )}
                              </Form.List>
                            </Panel>

                            {/* ANY OF (OR) Conditions */}
                            <Panel header="ANY OF (OR) - At least one condition must match" key="any_of">
                              <Form.List name={[name, 'conditions', 'any_of']}>
                                {(condFields, { add: addCond, remove: removeCond }) => (
                                  <>
                                    {condFields.map(({ key: condKey, name: condName }) => (
                                      <Row key={condKey} gutter={8} className="mb-2">
                                        <Col span={7}>
                                          <Form.Item name={[condName, 'field']} noStyle>
                                            <Select aria-label="Condition field" placeholder="Field" options={ASSET_FIELDS} />
                                          </Form.Item>
                                        </Col>
                                        <Col span={6}>
                                          <Form.Item name={[condName, 'operator']} noStyle>
                                            <Select aria-label="Condition operator" placeholder="Operator" options={OPERATORS} />
                                          </Form.Item>
                                        </Col>
                                        <Col span={9}>
                                          <Form.Item name={[condName, 'value']} noStyle>
                                            <Input aria-label="Condition value" placeholder="Value" />
                                          </Form.Item>
                                        </Col>
                                        <Col span={2}>
                                          <Button
                                            type="text"
                                            danger
                                            icon={<MinusCircleOutlined />}
                                            aria-label="Remove condition"
                                            onClick={() => removeCond(condName)}
                                          />
                                        </Col>
                                      </Row>
                                    ))}
                                    <Button
                                      type="dashed"
                                      onClick={() => addCond()}
                                      block
                                      icon={<PlusOutlined />}
                                      className="mt-2"
                                    >
                                      Add OR Condition
                                    </Button>
                                  </>
                                )}
                              </Form.List>
                            </Panel>

                            {/* NONE OF (NOT) Conditions */}
                            <Panel header="NONE OF (NOT) - No conditions should match" key="none_of">
                              <Form.List name={[name, 'conditions', 'none_of']}>
                                {(condFields, { add: addCond, remove: removeCond }) => (
                                  <>
                                    {condFields.map(({ key: condKey, name: condName }) => (
                                      <Row key={condKey} gutter={8} className="mb-2">
                                        <Col span={7}>
                                          <Form.Item name={[condName, 'field']} noStyle>
                                            <Select aria-label="Condition field" placeholder="Field" options={ASSET_FIELDS} />
                                          </Form.Item>
                                        </Col>
                                        <Col span={6}>
                                          <Form.Item name={[condName, 'operator']} noStyle>
                                            <Select aria-label="Condition operator" placeholder="Operator" options={OPERATORS} />
                                          </Form.Item>
                                        </Col>
                                        <Col span={9}>
                                          <Form.Item name={[condName, 'value']} noStyle>
                                            <Input aria-label="Condition value" placeholder="Value" />
                                          </Form.Item>
                                        </Col>
                                        <Col span={2}>
                                          <Button
                                            type="text"
                                            danger
                                            icon={<MinusCircleOutlined />}
                                            aria-label="Remove condition"
                                            onClick={() => removeCond(condName)}
                                          />
                                        </Col>
                                      </Row>
                                    ))}
                                    <Button
                                      type="dashed"
                                      onClick={() => addCond()}
                                      block
                                      icon={<PlusOutlined />}
                                      className="mt-2"
                                    >
                                      Add NOT Condition
                                    </Button>
                                  </>
                                )}
                              </Form.List>
                            </Panel>
                          </Collapse>

                          {/* Tags to Apply */}
                          <div className="mt-4">
                            <div className="font-medium mb-2">Tags to Apply:</div>
                            <Form.List name={[name, 'tags']}>
                              {(tagFields, { add: addTag, remove: removeTag }) => {
                                // Handle tags as object with key-value pairs
                                const tags = form.getFieldValue(['tagging_rules', name, 'tags']) || {};
                                return (
                                  <Space direction="vertical" style={{ width: '100%' }}>
                                    {Object.entries(tags).map(([tagKey, tagValue], idx) => (
                                      <Space key={idx}>
                                        <Input
                                          aria-label="Tag key"
                                          value={tagKey}
                                          placeholder="Key"
                                          onChange={(e) => {
                                            const newTags = { ...tags };
                                            delete newTags[tagKey];
                                            newTags[e.target.value] = tagValue;
                                            form.setFieldValue(['tagging_rules', name, 'tags'], newTags);
                                          }}
                                          style={{ width: 150 }}
                                        />
                                        <Input
                                          aria-label="Tag value"
                                          value={tagValue as string}
                                          placeholder="Value"
                                          onChange={(e) => {
                                            const newTags = { ...tags, [tagKey]: e.target.value };
                                            form.setFieldValue(['tagging_rules', name, 'tags'], newTags);
                                          }}
                                          style={{ width: 200 }}
                                        />
                                        <Button
                                          type="text"
                                          danger
                                          icon={<MinusCircleOutlined />}
                                          aria-label="Remove tag"
                                          onClick={() => {
                                            const newTags = { ...tags };
                                            delete newTags[tagKey];
                                            form.setFieldValue(['tagging_rules', name, 'tags'], newTags);
                                          }}
                                        />
                                      </Space>
                                    ))}
                                    <Button
                                      type="dashed"
                                      icon={<PlusOutlined />}
                                      onClick={() => {
                                        const newTags = { ...tags, '': '' };
                                        form.setFieldValue(['tagging_rules', name, 'tags'], newTags);
                                      }}
                                    >
                                      Add Tag
                                    </Button>
                                  </Space>
                                );
                              }}
                            </Form.List>
                          </div>
                        </Card>
                      ))}
                      <Button
                        type="primary"
                        onClick={() => add({
                          name: 'New Rule',
                          enabled: true,
                          conditions: {},
                          tags: {}
                        })}
                        block
                        icon={<PlusOutlined />}
                        className="mt-4"
                      >
                        Add Tagging Rule
                      </Button>

                      <div style={{ marginTop: '24px' }}>
                        <Button
                          type="primary"
                          htmlType="button"
                          loading={saving}
                          icon={<SaveOutlined />}
                          onClick={() =>
                            saveSection(
                              [['tagging_rules']],
                              'Tagging settings saved',
                              (payload) => updateCaasmTaggingRules(payload.tagging_rules),
                              buildPayload,
                            )
                          }
                        >
                          Save Tagging Settings
                        </Button>
                      </div>
                    </>
                  )}
                </Form.List>
              </div>
            </TabPane>

            {/* Cloud Accounts */}
            <TabPane tab="Cloud Accounts" key="cloud-accounts">
              <CloudAccountsClient defaultProvider="godaddy" />
            </TabPane>


            {/* Port Classification */}
            <TabPane tab="Port Classification" key="ports">
              <div>
                <div className="mb-6">
                  <h3 className="text-lg font-semibold mb-2">High-Risk Port Library</h3>
                  <p className="text-gray-600">
                    Define ports that should be flagged as high-risk when exposed publicly.
                    These definitions are used in port search and risk scoring.
                  </p>
                </div>

                <Form.List name={['port_catalog', 'high_risk_ports']}>
                  {(fields, { add, remove }) => (
                    <>
                      <Table
                        dataSource={fields.map((field, idx) => ({
                          ...field,
                          ...form.getFieldValue(['port_catalog', 'high_risk_ports', idx]),
                          key: field.key,
                          index: idx,
                        }))}
                        columns={[
                          {
                            title: 'Port',
                            dataIndex: 'port',
                            width: 100,
                            render: (_, record: any) => (
                              <Form.Item name={[record.name, 'port']} noStyle rules={[{ required: true }]}>
                                <InputNumber aria-label="Port" min={1} max={65535} placeholder="Port" />
                              </Form.Item>
                            ),
                          },
                          {
                            title: 'Protocol',
                            dataIndex: 'protocol',
                            width: 120,
                            render: (_, record: any) => (
                              <Form.Item name={[record.name, 'protocol']} noStyle rules={[{ required: true }]}>
                                <Select aria-label="Protocol" placeholder="Protocol">
                                  <Option value="tcp">TCP</Option>
                                  <Option value="udp">UDP</Option>
                                </Select>
                              </Form.Item>
                            ),
                          },
                          {
                            title: 'Service',
                            dataIndex: 'service',
                            width: 150,
                            render: (_, record: any) => (
                              <Form.Item name={[record.name, 'service']} noStyle rules={[{ required: true }]}>
                                <Input aria-label="Service name" placeholder="Service name" />
                              </Form.Item>
                            ),
                          },
                          {
                            title: 'Risk Level',
                            dataIndex: 'risk_level',
                            width: 140,
                            render: (_, record: any) => (
                              <Form.Item name={[record.name, 'risk_level']} noStyle rules={[{ required: true }]}>
                                <Select aria-label="Risk level" placeholder="Risk">
                                  {RISK_LEVELS.map(r => (
                                    <Option key={r.value} value={r.value}>
                                      <Tag color={r.color}>{r.label}</Tag>
                                    </Option>
                                  ))}
                                </Select>
                              </Form.Item>
                            ),
                          },
                          {
                            title: 'Reason',
                            dataIndex: 'reason',
                            render: (_, record: any) => (
                              <Form.Item name={[record.name, 'reason']} noStyle rules={[{ required: true }]}>
                                <Input aria-label="Risk reason" placeholder="Why is this risky?" />
                              </Form.Item>
                            ),
                          },
                          {
                            title: 'Enabled',
                            dataIndex: 'enabled',
                            width: 100,
                            render: (_, record: any) => (
                              <Form.Item name={[record.name, 'enabled']} valuePropName="checked" noStyle>
                                <Switch aria-label="Enable high-risk port" />
                              </Form.Item>
                            ),
                          },
                          {
                            title: 'Action',
                            width: 80,
                            render: (_, record: any) => (
                              <Button
                                type="text"
                                danger
                                icon={<DeleteOutlined />}
                                aria-label="Remove high-risk port"
                                onClick={() => remove(record.name)}
                              />
                            ),
                          },
                        ]}
                        pagination={false}
                        size="small"
                      />
                      <Button
                        type="dashed"
                        onClick={() => add({
                          port: undefined,
                          protocol: 'tcp',
                          service: '',
                          risk_level: 'high',
                          reason: '',
                          enabled: true
                        })}
                        block
                        icon={<PlusOutlined />}
                        className="mt-4"
                      >
                        Add Port Definition
                      </Button>

                      <div style={{ marginTop: '24px' }}>
                        <Button
                          type="primary"
                          htmlType="button"
                          loading={saving}
                          icon={<SaveOutlined />}
                          onClick={() =>
                            saveSection(
                              [['port_catalog']],
                              'Port settings saved',
                              (payload) => updateCaasmPortCatalog(payload.port_catalog),
                              buildPayload,
                            )
                          }
                        >
                          Save Port Settings
                        </Button>
                      </div>
                    </>
                  )}
                </Form.List>
              </div>
            </TabPane>

            {/* Ephemeral Asset Policy */}
            <TabPane tab="Ephemeral Assets" key="ephemeral">
              <div className="max-w-2xl">
                <div className="mb-6">
                  <h3 className="text-lg font-semibold mb-2">TTL & Cleanup Policy</h3>
                  <p className="text-gray-600">
                    Configure how long ephemeral (short-lived) assets are retained before automatic cleanup.
                  </p>
                </div>

                <Form.Item
                  label={
                    <span>
                      TTL (Time To Live)
                      <Tooltip title="Hours after last_seen_at before asset is considered stale">
                        <InfoCircleOutlined className="ml-2 text-gray-400" />
                      </Tooltip>
                    </span>
                  }
                  name={['ephemeral_asset_policy', 'ttl_hours']}
                  rules={[{ required: true, type: 'number', min: 1, max: 720 }]}
                >
                  <InputNumber
                    min={1}
                    max={720}
                    addonAfter="hours"
                    style={{ width: 200 }}
                  />
                </Form.Item>

                <Form.Item
                  label="Enable Automatic Cleanup"
                  name={['ephemeral_asset_policy', 'enable_auto_cleanup']}
                  valuePropName="checked"
                >
                  <Switch
                    checkedChildren="Enabled"
                    unCheckedChildren="Disabled"
                  />
                </Form.Item>

                <Form.Item
                  label={
                    <span>
                      Preserve History
                      <Tooltip title="Keep deleted assets in asset_history table for audit trail">
                        <InfoCircleOutlined className="ml-2 text-gray-400" />
                      </Tooltip>
                    </span>
                  }
                  name={['ephemeral_asset_policy', 'preserve_history']}
                  valuePropName="checked"
                >
                  <Switch
                    checkedChildren="Yes"
                    unCheckedChildren="No"
                  />
                </Form.Item>

                <Form.Item
                  label={
                    <span>
                      Cleanup Schedule (Cron)
                      <Tooltip title="Cron expression for cleanup job (e.g., '0 */6 * * *' for every 6 hours)">
                        <InfoCircleOutlined className="ml-2 text-gray-400" />
                      </Tooltip>
                    </span>
                  }
                  name={['ephemeral_asset_policy', 'cleanup_cron_schedule']}
                >
                  <Input
                    placeholder="0 */6 * * *"
                    style={{ width: 300 }}
                  />
                </Form.Item>

                <Card className="mt-6 bg-blue-50">
                  <div className="text-sm">
                    <div className="font-semibold mb-2">Recommended Settings:</div>
                    <ul className="list-disc list-inside space-y-1 text-gray-700">
                      <li><strong>Auto-scaling instances:</strong> TTL = 1-6 hours</li>
                      <li><strong>Temporary test resources:</strong> TTL = 12-24 hours</li>
                      <li><strong>Short-term projects:</strong> TTL = 48-72 hours</li>
                    </ul>
                  </div>
                </Card>

                <div style={{ marginTop: '24px' }}>
                  <Button
                    type="primary"
                    htmlType="button"
                    loading={saving}
                    icon={<SaveOutlined />}
                    onClick={() =>
                      saveSection(
                        [['ephemeral_asset_policy']],
                        'Ephemeral settings saved',
                        (payload) => updateCaasmEphemeralPolicy(payload.ephemeral_asset_policy),
                        buildPayload,
                      )
                    }
                  >
                    Save Ephemeral Settings
                  </Button>
                </div>
              </div>
            </TabPane>

            {/* Discovery Intervals */}
            <TabPane tab="Discovery" key="discovery">
              <div className="max-w-xl">
                <p className="mb-6 text-gray-600">
                  Configure sync intervals (in minutes) for asset discovery from different cloud providers.
                </p>

                <Form.Item
                  label="AWS Sync Interval"
                  name={['discovery_intervals', 'aws']}
                  rules={[{ type: 'number', min: 1 }]}
                >
                  <InputNumber min={1} addonAfter="minutes" style={{ width: 200 }} />
                </Form.Item>

                <Form.Item
                  label="GCP Sync Interval"
                  name={['discovery_intervals', 'gcp']}
                  rules={[{ type: 'number', min: 1 }]}
                >
                  <InputNumber min={1} addonAfter="minutes" style={{ width: 200 }} />
                </Form.Item>

                <Form.Item
                  label="Azure Sync Interval"
                  name={['discovery_intervals', 'azure']}
                  rules={[{ type: 'number', min: 1 }]}
                >
                  <InputNumber min={1} addonAfter="minutes" style={{ width: 200 }} />
                </Form.Item>

                <Divider orientation="left">Public Exposure Scope</Divider>
                <Alert
                  type="info"
                  showIcon
                  className="mb-4"
                  message="Attack-surface filtering"
                  description="These controls keep full asset records but let you store only public IPs and/or public ports. Use them when you want a narrower public-exposure view instead of a full private-and-public inventory."
                />

                <Row gutter={16}>
                  <Col span={8}>
                    <Form.Item
                      label={
                        <LabelWithHelp
                          label="IP collection scope"
                          help={helpWithRecommendation(
                            "Controls whether CAASM stores every discovered IP asset or only IPs already classified as public.",
                            "Keep `All IPs` for complete inventory. Choose `Public IPs only` when you only want internet-exposed IP visibility."
                          )}
                        />
                      }
                      name={['collection_scope', 'ip_collection_scope']}
                    >
                      <Select
                        options={[
                          { label: 'All IPs', value: 'all' },
                          { label: 'Public IPs only', value: 'public_only' },
                        ]}
                      />
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Form.Item
                      label={
                        <LabelWithHelp
                          label="Port collection scope"
                          help={helpWithRecommendation(
                            "Controls whether CAASM stores every discovered port or only ports whose exposure is already classified as public.",
                            "Keep `All ports` for full inventory. Choose `Public ports only` when you only care about internet-reachable exposure."
                          )}
                        />
                      }
                      name={['collection_scope', 'port_collection_scope']}
                    >
                      <Select
                        options={[
                          { label: 'All ports', value: 'all' },
                          { label: 'Public ports only', value: 'public_only' },
                        ]}
                      />
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Form.Item
                      label={
                        <LabelWithHelp
                          label="Domain collection scope"
                          help={helpWithRecommendation(
                            "Controls whether the Route53 collector reads every hosted zone or skips private hosted zones during collection.",
                            "Keep `All domains` for complete Route53 coverage. Choose `Public domains only` when you only want public Route53 hosted zones and the DNS records collected from them."
                          )}
                        />
                      }
                      name={['collection_scope', 'domain_collection_scope']}
                    >
                      <Select
                        options={[
                          { label: 'All domains', value: 'all' },
                          { label: 'Public domains only', value: 'public_only' },
                        ]}
                      />
                    </Form.Item>
                  </Col>
                </Row>
                <Paragraph type="secondary" style={{ marginTop: -8 }}>
                  Assets are still retained when public-only mode is enabled. Private IP assets and private ports are still filtered at ingest time. Domain scope only affects Route53 collection and skips private hosted zones before their DNS records are fetched.
                </Paragraph>
              </div>
              <div style={{ marginTop: '24px' }}>
                <Button
                  type="primary"
                  htmlType="button"
                  loading={saving}
                  icon={<SaveOutlined />}
                  onClick={() =>
                    saveSection(
                      [['discovery_intervals'], ['collection_scope']],
                      'Discovery settings saved',
                      (payload) => updateCaasmConfig(payload),
                      buildPayload,
                    )
                  }
                >
                  Save Discovery Settings
                </Button>
              </div>
            </TabPane>

            {/* Sync Settings */}
            <TabPane tab="Sync Settings" key="sync">
              <div>
                <p className="mb-6 text-gray-600 max-w-2xl">
                  Configure the data collection mode. Choose between using a local Redis queue or invoking a lightweight agent (previously &quot;serverless&quot;).
                </p>

                <div className="max-w-xl">
                  <Form.Item
                    label="Sync Mode"
                    name={['sync_settings', 'mode']}
                    rules={[{ required: true, message: 'Please select a sync mode' }]}
                  >
                    <Select placeholder="Select mode">
                      <Option value="queue">Queue (Redis)</Option>
                      <Option value="serverless">Serverless</Option>
                    </Select>
                  </Form.Item>

                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) =>
                      prevValues.sync_settings?.mode !== currentValues.sync_settings?.mode
                    }
                  >
                    {({ getFieldValue }) =>
                      getFieldValue(['sync_settings', 'mode']) === 'serverless' ? (
                        <Form.Item
                          label="Agent Function Name"
                          name={['sync_settings', 'lambda_function_name']}
                          help="Optional label for the simulated agent."
                        >
                          <Input placeholder="e.g., caasm-collector" />
                        </Form.Item>
                      ) : null
                    }
                  </Form.Item>

                  <Form.Item
                    label="Running job timeout (minutes)"
                    name={['sync_settings', 'running_timeout_minutes']}
                    help="Zombie reaper marks running sync jobs as failed after this timeout. Use a higher value for large AWS accounts."
                    rules={[{ required: true, message: 'Please enter a running timeout' }]}
                  >
                    <InputNumber min={1} style={{ width: '100%' }} placeholder="60" />
                  </Form.Item>

                  <Form.Item
                    label="Execution timeout (minutes)"
                    name={['sync_settings', 'execution_timeout_minutes']}
                    help="Controls the live sync execution budget. This can stop an in-flight job before it reaches a complete snapshot."
                    rules={[{ required: true, message: 'Please enter an execution timeout' }]}
                  >
                    <InputNumber min={1} style={{ width: '100%' }} placeholder="30" />
                  </Form.Item>

                  <Form.Item
                    label="Queued job timeout (minutes)"
                    name={['sync_settings', 'queued_timeout_minutes']}
                    help="Queued sync jobs are marked failed after this timeout if they are not picked up by workers."
                    rules={[{ required: true, message: 'Please enter a queued timeout' }]}
                  >
                    <InputNumber min={1} style={{ width: '100%' }} placeholder="30" />
                  </Form.Item>

                  <Paragraph type="secondary" style={{ marginTop: -8 }}>
                    Execution timeout controls the live sync run. Running and queued timeouts only affect the repository reaper. Keep execution timeout high enough for large accounts; runtime-specific limits may still apply in lightweight agent mode.
                  </Paragraph>
                </div>

                <div style={{ marginTop: '24px' }}>
                  <Button
                    type="primary"
                    htmlType="button"
                    loading={saving}
                    icon={<SaveOutlined />}
                    onClick={() =>
                      saveSection(
                        [['sync_settings']],
                        'Sync settings saved',
                        (payload) => updateCaasmSyncSettings(payload.sync_settings),
                        buildPayload,
                      )
                    }
                  >
                    Save Sync Settings
                  </Button>
                </div>
              </div>
            </TabPane>

            {/* Throttling */}
            <TabPane tab="Throttling" key="throttling">
              <div className="max-w-xl">
                {(configEnvelope?.effective_throttling || configEnvelope?.throttling_contract) && (
                  <Card size="small" className="mb-4 bg-slate-50 border-slate-200">
                    <Space direction="vertical" size="small" style={{ width: '100%' }}>
                      <div>
                        <strong>Effective throttling</strong>
                        <div className="text-gray-500 text-sm">
                          These are the backend-resolved values after defaults and hard safety caps are applied.
                        </div>
                      </div>
                      <Space wrap>
                        <Tag color={configEnvelope?.effective_throttling?.enabled ? 'green' : 'default'}>
                          {configEnvelope?.effective_throttling?.enabled ? 'Throttling enabled' : 'Throttling disabled'}
                        </Tag>
                        <Tag color="default">
                          {configEnvelope?.throttling_contract?.override_policy ?? 'Override policy unavailable'}
                        </Tag>
                        <Tag color="default">
                          {configEnvelope?.throttling_contract?.coordination_mode ?? 'Coordination mode unavailable'}
                        </Tag>
                      </Space>
                      {configEnvelope?.effective_throttling && (
                        <Row gutter={[12, 12]}>
                          <Col span={12}>
                            <EffectiveValue
                              label="Token capacity"
                              help={helpWithRecommendation(
                                "The burst size the backend is actually using after defaults, overrides, and hard caps are resolved.",
                                "Keep 20 unless you have a proven need for larger bursts and AWS APIs remain stable."
                              )}
                              value={configEnvelope.effective_throttling.token_capacity ?? '-'}
                            />
                          </Col>
                          <Col span={12}>
                            <EffectiveValue
                              label="Refill/sec"
                              help={helpWithRecommendation(
                                "The sustained request refill rate the backend is actually using per second.",
                                "Keep 10 for general use; lower it if you see frequent throttling, raise it only with evidence."
                              )}
                              value={configEnvelope.effective_throttling.token_refill_per_sec ?? '-'}
                            />
                          </Col>
                          <Col span={12}>
                            <EffectiveValue
                              label="Max concurrency"
                              help={helpWithRecommendation(
                                "The highest number of concurrent collection workers the backend will currently allow.",
                                "Keep 5 unless you have measured headroom and need more throughput."
                              )}
                              value={configEnvelope.effective_throttling.max_concurrency ?? '-'}
                            />
                          </Col>
                          <Col span={12}>
                            <EffectiveValue
                              label="Min concurrency"
                              help={helpWithRecommendation(
                                "The lowest adaptive concurrency floor the backend will use when throttling down.",
                                "Keep 2 so collection can slow down safely without stalling completely."
                              )}
                              value={configEnvelope.effective_throttling.min_concurrency ?? '-'}
                            />
                          </Col>
                          <Col span={12}>
                            <EffectiveValue
                              label="Circuit threshold"
                              help={helpWithRecommendation(
                                "How many throttle events are currently allowed before the circuit breaker opens.",
                                "Start around 3 to 6. Use lower values for fragile accounts and higher values only if throttling is noisy but harmless."
                              )}
                              value={configEnvelope.effective_throttling.circuit_breaker?.threshold ?? '-'}
                            />
                          </Col>
                          <Col span={12}>
                            <EffectiveValue
                              label="Circuit cool-off"
                              help={helpWithRecommendation(
                                "How long the backend will keep a circuit open before retrying the affected scope.",
                                "Start at 30 to 60 seconds; extend it for accounts that repeatedly hit AWS limits."
                              )}
                              value={configEnvelope.effective_throttling.circuit_breaker?.cool_off_sec ?? '-'}
                            />
                          </Col>
                        </Row>
                      )}
                      {configEnvelope?.throttling_contract && (
                        <Alert
                          type="info"
                          showIcon
                          message="Hard safety caps"
                          description={`Out-of-range throttling values are rejected. Override policy: ${configEnvelope.throttling_contract.override_policy}. Coordination mode: ${configEnvelope.throttling_contract.coordination_mode}.`}
                        />
                      )}
                    </Space>
                  </Card>
                )}
                {throttlingPresetEntries.length > 0 && (
                  <Card size="small" className="mb-4 bg-white border-dashed border-slate-300">
                    <Space direction="vertical" size="small" style={{ width: '100%' }}>
                      <div>
                        <strong>Throttling presets</strong>
                        <div className="text-gray-500 text-sm">
                          Apply a backend-provided preset to the draft form. This only fills the fields; nothing is saved until you click Save Throttling Settings.
                        </div>
                      </div>
                      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', width: '100%' }}>
                        <Select
                          style={{ flex: '1 1 320px', minWidth: 0 }}
                          value={selectedThrottlingPresetKey}
                          onChange={setSelectedThrottlingPresetKey}
                          options={throttlingPresetEntries.map((entry) => ({
                            value: entry.key,
                            label: `${entry.preset.label}${entry.preset.description ? ` - ${entry.preset.description}` : ''}`,
                          }))}
                        />
                        <Button
                          onClick={handleApplyThrottlingPreset}
                          disabled={!selectedThrottlingPreset}
                          style={{ flex: '0 0 auto' }}
                        >
                          Apply
                        </Button>
                      </div>
                      {selectedThrottlingPreset && (
                        <Descriptions size="small" column={1} bordered>
                          <Descriptions.Item label="Preset">
                            {selectedThrottlingPreset.preset.label}
                          </Descriptions.Item>
                          {selectedThrottlingPreset.preset.description && (
                            <Descriptions.Item label="Description">
                              {selectedThrottlingPreset.preset.description}
                            </Descriptions.Item>
                          )}
                        </Descriptions>
                      )}
                    </Space>
                  </Card>
                )}
                <Form.Item
                  label={
                    <LabelWithHelp
                      label="Enable throttling"
                      help={helpWithRecommendation(
                        "Turns the shared AWS throttling safeguards on or off for CAASM collection.",
                        "Keep this enabled in normal operation so token limits, adaptive slowdown, and runtime coordination keep protecting AWS APIs."
                      )}
                    />
                  }
                  name={['throttling', 'enabled']}
                  valuePropName="checked"
                  style={{ marginTop: 20 }}
                >
                  <Switch />
                </Form.Item>
                <Alert
                  type="info"
                  showIcon
                  className="mb-4"
                  message="Global defaults first, account overrides second"
                  description="These values define the shared default throttling envelope. AWS account overrides may inherit these values or narrow them for a single account, but they cannot exceed the backend safety caps or bypass runtime coordination."
                />
                <Row gutter={16} style={{ marginTop: 16 }}>
                  <Col span={12}>
                    <Form.Item
                      label={
                        <LabelWithHelp
                          label="Token capacity"
                          help={helpWithRecommendation(
                            "How many requests the shared default bucket can absorb in a short burst before the collector has to slow down.",
                            "Start with 20. Lower it if AWS throttles early; only raise it when you need short bursts and have evidence the account can tolerate them."
                          )}
                        />
                      }
                      name={['throttling', 'token_capacity']}
                    >
                      <InputNumber min={0} style={{ width: '100%' }} placeholder="e.g., 20" />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      label={
                        <LabelWithHelp
                          label="Refill per sec"
                          help={helpWithRecommendation(
                            "How quickly tokens are added back into the shared default bucket each second. This controls the steady-state request rate.",
                            "Start with 10. Reduce it first if you see rate pressure; increase it only after confirming AWS limits are still healthy."
                          )}
                        />
                      }
                      name={['throttling', 'token_refill_per_sec']}
                    >
                      <InputNumber min={0} step={0.5} style={{ width: '100%' }} placeholder="e.g., 10" />
                    </Form.Item>
                  </Col>
                </Row>
                <Row gutter={16}>
                  <Col span={12}>
                    <Form.Item
                      label={
                        <LabelWithHelp
                          label="Adaptive threshold"
                          help={helpWithRecommendation(
                            "How many throttle-like signals can appear inside the adaptive window before the collector starts reducing pressure automatically.",
                            "Start with 3. Lower it for fragile accounts; raise it only if harmless noise is causing unnecessary slowdowns."
                          )}
                        />
                      }
                      name={['throttling', 'adaptive_threshold']}
                    >
                      <InputNumber min={0} style={{ width: '100%' }} placeholder="e.g., 3" />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      label={
                        <LabelWithHelp
                          label="Adaptive window (sec)"
                          help={helpWithRecommendation(
                            "The time window used to count recent throttle pressure for adaptive slowdown decisions.",
                            "Start with 60 seconds. Use a shorter window for quicker reactions, or a longer one if you want smoother, less jumpy adaptation."
                          )}
                        />
                      }
                      name={['throttling', 'adaptive_window_sec']}
                    >
                      <InputNumber min={0} style={{ width: '100%' }} placeholder="e.g., 60" />
                    </Form.Item>
                  </Col>
                </Row>
                <Row gutter={16}>
                  <Col span={12}>
                    <Form.Item
                      label={
                        <LabelWithHelp
                          label="Cool-off (sec)"
                          help={helpWithRecommendation(
                            "How long the collector should wait after adaptive throttling decides it needs to back off.",
                            "Start with 30 seconds. Increase it for accounts that keep re-throttling immediately after recovery."
                          )}
                        />
                      }
                      name={['throttling', 'cool_off_sec']}
                    >
                      <InputNumber min={0} style={{ width: '100%' }} placeholder="e.g., 30" />
                    </Form.Item>
                  </Col>
                </Row>
                <Divider orientation="left">Circuit breaker</Divider>
                <Paragraph type="secondary">
                  Repeated throttling can trip a circuit breaker so the collector cools off instead of repeatedly hammering AWS.
                </Paragraph>
                <Row gutter={16}>
                  <Col span={12}>
                    <Form.Item
                      label={
                        <LabelWithHelp
                          label="Throttle events before open"
                          help={helpWithRecommendation(
                            "How many repeated throttle events are allowed before the circuit breaker opens for the affected scope.",
                            "Start around 3 to 6. Lower values are safer; higher values are more aggressive."
                          )}
                        />
                      }
                      name={['throttling', 'circuit_breaker', 'threshold']}
                    >
                      <InputNumber min={0} style={{ width: '100%' }} placeholder="e.g., 3" />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      label={
                        <LabelWithHelp
                          label="Open-state cool-off (sec)"
                          help={helpWithRecommendation(
                            "How long the circuit breaker stays open before the collector is allowed to test the AWS scope again.",
                            "Start with 30 to 60 seconds. Use a longer value if AWS continues throttling after each retry."
                          )}
                        />
                      }
                      name={['throttling', 'circuit_breaker', 'cool_off_sec']}
                    >
                      <InputNumber min={0} style={{ width: '100%' }} placeholder="e.g., 30" />
                    </Form.Item>
                  </Col>
                </Row>
                <Row gutter={16}>
                  <Col span={12}>
                    <Form.Item
                      label={
                        <LabelWithHelp
                          label="Max concurrency"
                          help={helpWithRecommendation(
                            "The highest number of concurrent collection workers the shared default throttling model should allow for AWS work.",
                            "Start with 5. For most environments, change refill rate before raising concurrency."
                          )}
                        />
                      }
                      name={['throttling', 'max_concurrency']}
                    >
                      <InputNumber min={1} style={{ width: '100%' }} placeholder="e.g., 5" />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      label={
                        <LabelWithHelp
                          label="Min concurrency"
                          help={helpWithRecommendation(
                            "The floor the adaptive limiter should not go below while it is throttling down.",
                            "Start with 2 so collection can slow down safely without collapsing to a near-stop."
                          )}
                        />
                      }
                      name={['throttling', 'min_concurrency']}
                    >
                      <InputNumber min={1} style={{ width: '100%' }} placeholder="e.g., 2" />
                    </Form.Item>
                  </Col>
                </Row>
                <Divider orientation="left">Service-aware limits</Divider>
                <Paragraph type="secondary">
                  Use these only for AWS services that need stricter protection than the global defaults. Leaving a field blank keeps the shared default.
                </Paragraph>
                {(configEnvelope?.throttling_contract?.supported_services || []).map((serviceKey) => (
                  <Card key={serviceKey} size="small" title={serviceKey.toUpperCase()} className="mb-4">
                    <Row gutter={16}>
                      <Col span={12}>
                        <Form.Item
                          label={
                            <LabelWithHelp
                              label="Token capacity"
                              help={helpWithRecommendation(
                                `Override the burst size just for ${serviceKey.toUpperCase()}.`,
                                "Leave this blank unless this service needs stricter protection than the global default."
                              )}
                            />
                          }
                          name={['throttling', 'service_limits', serviceKey, 'token_capacity']}
                        >
                          <InputNumber min={0} style={{ width: '100%' }} placeholder="Inherit global default" />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item
                          label={
                            <LabelWithHelp
                              label="Refill / sec"
                              help={helpWithRecommendation(
                                `Override the steady-state request refill rate just for ${serviceKey.toUpperCase()}.`,
                                "Leave this blank unless this service is a known throttling hotspot."
                              )}
                            />
                          }
                          name={['throttling', 'service_limits', serviceKey, 'token_refill_per_sec']}
                        >
                          <InputNumber min={0} step={0.5} style={{ width: '100%' }} placeholder="Inherit global default" />
                        </Form.Item>
                      </Col>
                    </Row>
                    <Row gutter={16}>
                      <Col span={12}>
                        <Form.Item
                          label={
                            <LabelWithHelp
                              label="Max concurrency"
                              help={helpWithRecommendation(
                                `Override the maximum concurrency just for ${serviceKey.toUpperCase()} calls.`,
                                "Leave this blank unless this service needs a lower per-service cap than the global default."
                              )}
                            />
                          }
                          name={['throttling', 'service_limits', serviceKey, 'max_concurrency']}
                        >
                          <InputNumber min={0} style={{ width: '100%' }} placeholder="Inherit global default" />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item
                          label={
                            <LabelWithHelp
                              label="Min concurrency"
                              help={helpWithRecommendation(
                                `Override the minimum adaptive concurrency just for ${serviceKey.toUpperCase()}.`,
                                "Leave this blank unless this service needs a stricter adaptive floor than the global default."
                              )}
                            />
                          }
                          name={['throttling', 'service_limits', serviceKey, 'min_concurrency']}
                        >
                          <InputNumber min={0} style={{ width: '100%' }} placeholder="Inherit global default" />
                        </Form.Item>
                      </Col>
                    </Row>
                  </Card>
                ))}
                <div style={{ marginTop: 24 }}>
                  <Button
                    type="primary"
                    htmlType="button"
                    loading={saving}
                    icon={<SaveOutlined />}
                    onClick={() =>
                      saveSection(
                        [['throttling']],
                        'Throttling settings saved',
                        (payload) => updateCaasmConfig(payload),
                        buildPayload,
                      )
                    }
                  >
                    Save Throttling Settings
                  </Button>
                </div>
              </div>
            </TabPane>
          </Tabs>
        </Card>
      </Form>
    </div >
  );
}

function buildMergedConfig(values: any, config: CaasmConfig): CaasmConfig {
  return {
    ...config,
    ...values,
    ephemeral_asset_policy: {
      ...DEFAULT_EPHEMERAL_POLICY,
      ...(values?.ephemeral_asset_policy || config?.ephemeral_asset_policy || {}),
    },
    discovery_intervals: {
      ...DEFAULT_DISCOVERY_INTERVALS,
      ...(values?.discovery_intervals || config?.discovery_intervals || {}),
    },
    collection_scope: {
      ...DEFAULT_COLLECTION_SCOPE,
      ...(values?.collection_scope || config?.collection_scope || {}),
    },
    throttling: mergeThrottlingConfig(
      config?.throttling as Partial<ThrottlingContract["defaults"]> | undefined,
      values?.throttling as Partial<ThrottlingContract["defaults"]> | undefined,
    ),
  };
}
