"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import {
  Alert,
  Button,
  Card,
  Collapse,
  Descriptions,
  Drawer,
  Form,
  Input,
  InputNumber,
  Modal,
  Select,
  Space,
  Table,
  Tag,
  Typography,
  Row,
  Col,
  Tooltip,
  message,
} from "antd";
import type { ColumnsType, TablePaginationConfig } from "antd/es/table";

import {
  createCloudAccount,
  deleteCloudAccount,
  fetchCloudAccountJobs,
  fetchCloudAccounts,
  fetchRuntimeStatus,
  startWorkers,
  testCloudAccount,
  triggerCloudAccountSync,
  updateCloudAccount,
} from "@/lib/api/caasm";
import { useAuth } from "@/lib/hooks/use-auth";
import type { CaasmSyncJob, CloudAccount, CloudAccountMetadata, RuntimeStatus } from "@/types/models";

const { Title, Paragraph, Text } = Typography;
const { Option } = Select;
const { Panel } = Collapse;

const providerOptions = ["aws", "gcp", "azure", "alibaba", "other"] as const;
const AWS_THROTTLE_KEYS = [
  "allowed_regions",
  "throttle_enabled",
  "throttle_tokens",
  "throttle_refill_per_sec",
  "throttle_max_concurrency",
  "throttle_min_concurrency",
] as const;

type AwsThrottleOverrideFormValue = {
  aws_role_arn?: string;
  aws_region?: string;
  aws_allowed_regions?: string[];
  aws_throttle_enabled?: "inherit" | "enabled" | "disabled";
  aws_throttle_tokens?: number;
  aws_throttle_refill_per_sec?: number;
  aws_throttle_max_concurrency?: number;
  aws_throttle_min_concurrency?: number;
};

const normalizeStringArray = (value: unknown): string[] => {
  if (Array.isArray(value)) {
    return value
      .map((item) => (typeof item === "string" ? item.trim() : ""))
      .filter((item): item is string => Boolean(item));
  }
  if (typeof value === "string") {
    return value
      .split(",")
      .map((item) => item.trim())
      .filter((item): item is string => Boolean(item));
  }
  return [];
};

const toOptionalNumber = (value: unknown): number | undefined => {
  if (value === undefined || value === null || value === "") {
    return undefined;
  }
  const parsed = typeof value === "number" ? value : Number(value);
  return Number.isFinite(parsed) ? parsed : undefined;
};

const stripAwsThrottleMetadata = (metadata: CloudAccountMetadata): Record<string, unknown> => {
  const fallback = { ...metadata };
  AWS_THROTTLE_KEYS.forEach((key) => {
    delete fallback[key];
  });
  return fallback;
};

const readAwsThrottleEnabled = (value: unknown): AwsThrottleOverrideFormValue["aws_throttle_enabled"] => {
  if (value === true) return "enabled";
  if (value === false) return "disabled";
  return "inherit";
};

const renderEffectiveThrottlingValue = (value: unknown) => {
  if (Array.isArray(value)) {
    return value.length ? value.join(", ") : "—";
  }
  if (typeof value === "boolean") {
    return value ? "Enabled" : "Disabled";
  }
  if (typeof value === "number") {
    return Number.isFinite(value) ? String(value) : "—";
  }
  if (typeof value === "string") {
    return value || "—";
  }
  return "—";
};

const renderContractHardCapValue = (value: unknown) => renderEffectiveThrottlingValue(value);

const getSyncFeedbackMessage = (
  job: CaasmSyncJob,
  schedulerRunning: boolean | undefined,
): { type: "success" | "info" | "warning"; content: string } => {
  const status = (job.status ?? "").toLowerCase();
  if (status === "running") {
    return {
      type: "info",
      content: "A sync job is already running for this account",
    };
  }
  if (status === "queued" || status === "pending") {
    return {
      type: "success",
      content: schedulerRunning === false
        ? "Manual sync job queued while scheduler is stopped"
        : "Sync job queued",
    };
  }
  return {
    type: "success",
    content: schedulerRunning === false
      ? "Manual sync request accepted while scheduler is stopped"
      : "Sync request accepted",
  };
};

function getRuntimeStatusSummary(status: RuntimeStatus | null) {
  if (!status) {
    return null;
  }

  const pressureSummary =
    status.runtime_pressure_cap != null
      ? `Shared cap: ${status.runtime_pressure_cap}${status.active_job_count != null ? `, active jobs: ${status.active_job_count}` : ""}.`
      : null;

  if (status.kill_switch_enabled) {
    return {
      type: "error" as const,
      message: "Emergency stop is enabled",
      description:
        "Manual syncs are blocked and runtime workers remain stopped until the emergency stop is disabled.",
      detail: pressureSummary,
    };
  }

  if (status.scheduler_running === false && status.workers_running) {
    return {
      type: "info" as const,
      message: "Scheduler is stopped, manual sync is still available",
      description:
        "Automatic scheduled syncs are paused, but you can still trigger manual sync jobs from this page while the worker pool is running.",
      detail: pressureSummary,
    };
  }

  if (!status.workers_running) {
    return {
      type: "warning" as const,
      message: "Worker pool is stopped",
      description:
        "Manual syncs can still be queued while workers are stopped, but they will not process until the worker pool is started. Scheduler state does not block queueing by itself.",
      detail: pressureSummary,
    };
  }

  return {
    type: "info" as const,
    message: "Worker pool is running",
    description:
      "Sync actions are available, but they can still be delayed when runtime coordination guards or the shared pressure cap are saturated.",
    detail: pressureSummary,
  };
}

function getSyncTooltip(status: RuntimeStatus | null) {
  if (!status) {
    return "Runtime status is still loading.";
  }
  if (status.kill_switch_enabled) {
    return "Emergency stop is enabled. Disable it before syncing this account.";
  }
  if (!status.workers_running) {
    return "Workers are stopped. Manual sync can still be queued, but it will wait until workers are started.";
  }
  if (status.scheduler_running === false) {
    return "Scheduler is stopped. Manual sync is still available from this page.";
  }
  if (status.runtime_pressure_cap != null && status.active_job_count != null && status.active_job_count >= status.runtime_pressure_cap) {
    return "The runtime is at its shared pressure cap. Sync may be deferred until capacity frees up.";
  }
  return "Sync is available, but runtime coordination guards can still defer work if the shared cap fills up.";
}

type CloudAccountsClientProps = {
  defaultProvider?: string;
};

export default function CloudAccountsClient({ defaultProvider }: CloudAccountsClientProps) {
  const resolvedDefaultProvider = providerOptions.includes(defaultProvider as (typeof providerOptions)[number])
    ? defaultProvider
    : undefined;
  const [records, setRecords] = useState<CloudAccount[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState<TablePaginationConfig>({ current: 1, pageSize: 10 });
  const [filters, setFilters] = useState({
    provider: undefined as string | undefined,
    status: undefined as string | undefined,
    q: "",
  });
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [editing, setEditing] = useState<CloudAccount | null>(null);
  const [form] = Form.useForm();
  const provider = Form.useWatch("provider", form);
  const { hasPermission } = useAuth();
  const canManage = hasPermission("caasm:manage_assets");
  const [jobsModalOpen, setJobsModalOpen] = useState(false);
  const [jobRecords, setJobRecords] = useState<CaasmSyncJob[]>([]);
  const [jobsLoading, setJobsLoading] = useState(false);
  const [selectedAccount, setSelectedAccount] = useState<CloudAccount | null>(null);
  const [jobsPagination, setJobsPagination] = useState<TablePaginationConfig>({ current: 1, pageSize: 10 });
  const [runtimeStatus, setRuntimeStatus] = useState<RuntimeStatus | null>(null);
  const [checkingRuntime, setCheckingRuntime] = useState(false);
  const runtimeSummary = useMemo(() => getRuntimeStatusSummary(runtimeStatus), [runtimeStatus]);
  const syncActionsDisabled = runtimeStatus
    ? runtimeStatus.kill_switch_enabled
    : false;
  const syncTooltip = useMemo(() => getSyncTooltip(runtimeStatus), [runtimeStatus]);

  const loadData = useCallback(
    async (page: number, pageSize: number) => {
      setLoading(true);
      try {
        const payload = await fetchCloudAccounts({
          page,
          page_size: pageSize,
          provider: filters.provider,
          status: filters.status,
          q: filters.q || undefined,
        });
        setRecords(payload.items ?? []);
        setPagination((prev) => ({ ...prev, total: payload.total ?? 0 }));
      } catch (error) {
        console.error("Failed to load cloud accounts", error);
        message.error("Failed to load cloud accounts");
      } finally {
        setLoading(false);
      }
    },
    [filters],
  );

  const currentPage = pagination.current ?? 1;
  const currentPageSize = pagination.pageSize ?? 10;

  const checkRuntimeStatus = useCallback(async () => {
    try {
      setCheckingRuntime(true);
      const status = await fetchRuntimeStatus();
      setRuntimeStatus(status);
    } catch (error) {
      console.error("Failed to check runtime status", error);
    } finally {
      setCheckingRuntime(false);
    }
  }, []);

  useEffect(() => {
    loadData(currentPage, currentPageSize);
    checkRuntimeStatus();
  }, [loadData, currentPage, currentPageSize, checkRuntimeStatus]);

  const parseMetadata = (value?: string) => {
    if (!value) {
      return {};
    }
    try {
      return JSON.parse(value);
    } catch {
      throw new Error("Metadata must be valid JSON");
    }
  };

  const openDrawer = useCallback(
    (record?: CloudAccount) => {
      setEditing(record ?? null);
      setDrawerOpen(true);
      form.resetFields();
      if (record) {
        const metadata = (record.metadata ?? {}) as CloudAccountMetadata;
        const awsFallback = record.provider === "aws" ? stripAwsThrottleMetadata(metadata) : metadata;
        form.setFieldsValue({
          name: record.name,
          provider: record.provider,
          external_id: record.external_id,
          status: record.status,
          metadata: JSON.stringify(awsFallback ?? {}, null, 2),
          aws_role_arn: metadata.role_arn || "",
          aws_region: metadata.region || "",
          aws_allowed_regions: normalizeStringArray(metadata.allowed_regions),
          aws_throttle_enabled: readAwsThrottleEnabled(metadata.throttle_enabled),
          aws_throttle_tokens: metadata.throttle_tokens,
          aws_throttle_refill_per_sec: metadata.throttle_refill_per_sec,
          aws_throttle_max_concurrency: metadata.throttle_max_concurrency,
          aws_throttle_min_concurrency: metadata.throttle_min_concurrency,
        });
      } else {
        form.setFieldsValue({
          status: "active",
          provider: resolvedDefaultProvider,
          metadata: JSON.stringify({}, null, 2),
          aws_role_arn: "",
          aws_region: "us-east-1",
          aws_allowed_regions: [],
          aws_throttle_enabled: "inherit",
          aws_throttle_tokens: undefined,
          aws_throttle_refill_per_sec: undefined,
          aws_throttle_max_concurrency: undefined,
          aws_throttle_min_concurrency: undefined,
        });
      }
    },
    [resolvedDefaultProvider, form],
  );

  const handleDrawerSubmit = async () => {
    try {
      const values = await form.validateFields();
      const metadataObj = parseMetadata(values.metadata) as Record<string, unknown>;

      if (values.provider === "aws") {
        if (values.aws_role_arn) {
          metadataObj.role_arn = String(values.aws_role_arn).trim();
        } else {
          delete metadataObj.role_arn;
        }
        if (values.aws_region) {
          metadataObj.region = String(values.aws_region).trim();
        } else {
          delete metadataObj.region;
        }

        const allowedRegions = normalizeStringArray(values.aws_allowed_regions);
        if (allowedRegions.length > 0) {
          metadataObj.allowed_regions = allowedRegions;
        } else {
          delete metadataObj.allowed_regions;
        }

        if (values.aws_throttle_enabled === "enabled") {
          metadataObj.throttle_enabled = true;
        } else if (values.aws_throttle_enabled === "disabled") {
          metadataObj.throttle_enabled = false;
        } else {
          delete metadataObj.throttle_enabled;
        }

        const throttleTokens = toOptionalNumber(values.aws_throttle_tokens);
        const throttleRefill = toOptionalNumber(values.aws_throttle_refill_per_sec);
        const throttleMax = toOptionalNumber(values.aws_throttle_max_concurrency);
        const throttleMin = toOptionalNumber(values.aws_throttle_min_concurrency);

        if (throttleTokens !== undefined) {
          metadataObj.throttle_tokens = throttleTokens;
        } else {
          delete metadataObj.throttle_tokens;
        }
        if (throttleRefill !== undefined) {
          metadataObj.throttle_refill_per_sec = throttleRefill;
        } else {
          delete metadataObj.throttle_refill_per_sec;
        }
        if (throttleMax !== undefined) {
          metadataObj.throttle_max_concurrency = throttleMax;
        } else {
          delete metadataObj.throttle_max_concurrency;
        }
        if (throttleMin !== undefined) {
          metadataObj.throttle_min_concurrency = throttleMin;
        } else {
          delete metadataObj.throttle_min_concurrency;
        }
      }

      const payload = {
        name: values.name,
        provider: values.provider,
        external_id: values.external_id,
        status: values.status,
        metadata: metadataObj,
      };

      if (editing) {
        await updateCloudAccount(editing.id, payload);
        message.success(`Cloud account updated - Environment: ${metadataObj.environment || "default"}`);
      } else {
        await createCloudAccount(payload);
        message.success(`Cloud account created - Environment: ${metadataObj.environment || "default"}`);
      }
      setDrawerOpen(false);
      loadData(pagination.current ?? 1, pagination.pageSize ?? 10);
    } catch (error: any) {
      console.error("Error saving cloud account:", error);
      if (error instanceof Error) {
        message.error(error.message);
      } else if (error?.response?.data?.message) {
        message.error(error.response.data.message);
      } else {
        message.error("Failed to save cloud account");
      }
    }
  };

  const handleDelete = useCallback(
    (record: CloudAccount) => {
      Modal.confirm({
        title: `Delete ${record.name}?`,
        content: "This removes the account and any pending sync jobs associated with it.",
        okType: "danger",
        onOk: async () => {
          await deleteCloudAccount(record.id);
          message.success("Cloud account deleted");
          loadData(pagination.current ?? 1, pagination.pageSize ?? 10);
        },
      });
    },
    [loadData, pagination],
  );

  const handleTest = useCallback(async (record: CloudAccount) => {
    try {
      const result = await testCloudAccount(record.id);
      message.success(result.message);
    } catch (error) {
      console.error("Failed to test account", error);
      message.error("Test failed");
    }
  }, []);

  const handleSync = useCallback(async (record: CloudAccount) => {
    try {
      const status = await fetchRuntimeStatus();
      if (!status.workers_running) {
        Modal.confirm({
          title: "Worker Pool Not Running",
          content: (
            <div>
              <p>The worker pool is currently stopped. Manual sync is still allowed, but queued jobs won&apos;t process until workers are started.</p>
              {status.scheduler_running === false ? (
                <p>The scheduler is also stopped, but that does not block this manual sync and will remain stopped unless you start it separately.</p>
              ) : null}
              <p>Would you like to start the worker pool now?</p>
            </div>
          ),
          okText: "Start Workers & Sync",
          cancelText: "Queue Only",
          onOk: async () => {
            try {
              await startWorkers();
              message.success("Worker pool started");
              const job = await triggerCloudAccountSync(record.id);
              const feedback = getSyncFeedbackMessage(job, status.scheduler_running);
              message[feedback.type](
                feedback.type === "success" && status.scheduler_running !== false
                  ? "Sync job queued and will process shortly"
                  : feedback.content,
              );
              setRuntimeStatus((prev) => (prev ? { ...prev, workers_running: true } : prev));
            } catch (error) {
              console.error("Failed to start workers or queue sync", error);
              message.error("Failed to start workers");
            }
          },
          onCancel: async () => {
            const job = await triggerCloudAccountSync(record.id);
            const feedback = getSyncFeedbackMessage(job, status.scheduler_running);
            message[feedback.type](
              feedback.type === "success"
                ? "Sync job queued but workers are not running"
                : feedback.content,
            );
          },
        });
        return;
      }

      const job = await triggerCloudAccountSync(record.id);
      const feedback = getSyncFeedbackMessage(job, status.scheduler_running);
      message[feedback.type](feedback.content);
    } catch (error) {
      console.error("Failed to queue sync", error);
      message.error("Failed to queue sync job");
    }
  }, []);

  const loadJobs = useCallback(async (accountId: number, page: number, pageSize: number) => {
    setJobsLoading(true);
    try {
      const payload = await fetchCloudAccountJobs(accountId, { page, page_size: pageSize });
      setJobRecords(payload.items ?? []);
      setJobsPagination((prev) => ({ ...prev, total: payload.total ?? 0, current: page, pageSize }));
    } catch (error) {
      console.error("Failed to load sync jobs", error);
      message.error("Failed to load jobs");
    } finally {
      setJobsLoading(false);
    }
  }, []);

  const openJobs = useCallback(
    async (record: CloudAccount) => {
      setSelectedAccount(record);
      setJobsModalOpen(true);
      await loadJobs(record.id, jobsPagination.current ?? 1, jobsPagination.pageSize ?? 10);
    },
    [jobsPagination, loadJobs],
  );

  const columns: ColumnsType<CloudAccount> = useMemo(
    () => [
      {
        title: "Name",
        dataIndex: "name",
        render: (value: string, record) => (
          <Space direction="vertical" size={0}>
            <Text strong>{value}</Text>
            <Text type="secondary" style={{ fontSize: 12 }}>
              {record.external_id}
            </Text>
          </Space>
        ),
      },
      {
        title: "Provider",
        dataIndex: "provider",
        render: (value: string) => (
          <Space>
            <span>{value?.toUpperCase()}</span>
          </Space>
        ),
      },
      {
        title: "Status",
        dataIndex: "status",
        render: (value: string) => <Tag color={value === "active" ? "green" : "default"}>{value?.toUpperCase()}</Tag>,
      },
      {
        title: "Actions",
        dataIndex: "actions",
        render: (_, record) => (
          <Space>
            <Button type="link" size="small" onClick={() => openJobs(record)}>
              Jobs
            </Button>
            {canManage && (
              <>
                <Button type="link" size="small" onClick={() => openDrawer(record)}>
                  Edit
                </Button>
                <Button type="link" size="small" onClick={() => handleTest(record)}>
                  Test
                </Button>
                <Tooltip title={syncTooltip}>
                  <span>
                    <Button
                      type="link"
                      size="small"
                      onClick={() => handleSync(record)}
                      disabled={syncActionsDisabled}
                    >
                      Sync
                    </Button>
                  </span>
                </Tooltip>
                <Button type="link" danger size="small" onClick={() => handleDelete(record)}>
                  Delete
                </Button>
              </>
            )}
          </Space>
        ),
      },
    ],
    [canManage, handleDelete, handleSync, handleTest, openDrawer, openJobs, syncActionsDisabled, syncTooltip],
  );

  const handleStartWorkersFromBanner = async () => {
    try {
      setCheckingRuntime(true);
      await startWorkers();
      message.success("Worker pool started successfully");
      await checkRuntimeStatus();
    } catch (error) {
      console.error("Failed to start workers", error);
      message.error("Failed to start worker pool");
    } finally {
      setCheckingRuntime(false);
    }
  };

  return (
    <Space direction="vertical" size={24} style={{ width: "100%" }}>
      {runtimeSummary && (
        <Alert
          type={runtimeSummary.type}
          showIcon
          message={runtimeSummary.message}
          description={
            <Space direction="vertical" size={4}>
              <span>{runtimeSummary.description}</span>
              {runtimeSummary.detail ? <span>{runtimeSummary.detail}</span> : null}
            </Space>
          }
          action={
            runtimeStatus && !runtimeStatus.kill_switch_enabled && !runtimeStatus.workers_running ? (
              <Button size="small" type="primary" onClick={handleStartWorkersFromBanner} loading={checkingRuntime}>
                Start Workers
              </Button>
            ) : null
          }
          closable
        />
      )}
      <Card>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <Space direction="vertical" size={8}>
            <Title level={3} style={{ margin: 0 }}>
              Cloud Accounts
            </Title>
            <Paragraph type="secondary" style={{ marginBottom: 0 }}>
              Connected AWS, Azure, and GCP accounts powering CAASM collection.
            </Paragraph>
            {runtimeStatus ? (
              <Space size={8} wrap>
                <Tag color={runtimeStatus.workers_running ? "green" : "orange"}>
                  Workers {runtimeStatus.workers_running ? "running" : "stopped"}
                </Tag>
                <Tag color={runtimeStatus.scheduler_running ? "blue" : "gold"}>
                  Scheduler {runtimeStatus.scheduler_running ? "running" : "stopped"}
                </Tag>
                <Tag color={runtimeStatus.kill_switch_enabled ? "red" : "green"}>
                  Emergency stop {runtimeStatus.kill_switch_enabled ? "enabled" : "disabled"}
                </Tag>
                <Tag color={runtimeStatus.runtime_pressure_cap ? "blue" : "default"}>
                  {runtimeStatus.runtime_pressure_cap != null
                    ? `Pressure cap ${runtimeStatus.runtime_pressure_cap}`
                    : "No pressure cap reported"}
                </Tag>
                {runtimeStatus.active_job_count != null ? (
                  <Tag color="gold">Active jobs {runtimeStatus.active_job_count}</Tag>
                ) : null}
              </Space>
            ) : null}
          </Space>
          {canManage && (
            <Button type="primary" onClick={() => openDrawer()}>
              Add account
            </Button>
          )}
        </div>

        <Space style={{ marginTop: 16 }} size={12}>
          <Select
            id="cloud-account-filter-provider"
            aria-label="Filter by provider"
            placeholder="Provider"
            allowClear
            style={{ width: 180 }}
            value={filters.provider}
            onChange={(value) => {
              setFilters((prev) => ({ ...prev, provider: value }));
              setPagination((prev) => ({ ...prev, current: 1 }));
            }}
          >
            {providerOptions.map((option) => (
              <Option key={option} value={option}>
                {option.toUpperCase()}
              </Option>
            ))}
          </Select>
          <Select
            id="cloud-account-filter-status"
            aria-label="Filter by status"
            placeholder="Status"
            allowClear
            style={{ width: 160 }}
            value={filters.status}
            onChange={(value) => {
              setFilters((prev) => ({ ...prev, status: value }));
              setPagination((prev) => ({ ...prev, current: 1 }));
            }}
          >
            <Option value="active">Active</Option>
            <Option value="inactive">Inactive</Option>
          </Select>
          <Input.Search
            id="cloud-account-filter-query"
            aria-label="Search cloud accounts"
            allowClear
            placeholder="Search name or external ID"
            value={filters.q}
            style={{ width: 240 }}
            onChange={(event) => {
              setFilters((prev) => ({ ...prev, q: event.target.value }));
              setPagination((prev) => ({ ...prev, current: 1 }));
            }}
          />
        </Space>

        <Table
          style={{ marginTop: 16 }}
          rowKey="id"
          columns={columns}
          dataSource={records}
          loading={loading}
          pagination={pagination}
          onChange={(p) => {
            setPagination((prev) => ({ ...prev, current: p.current, pageSize: p.pageSize }));
            loadData(p.current ?? 1, p.pageSize ?? 10);
          }}
        />
      </Card>

      <Drawer
        title={editing ? "Edit Cloud Account" : "Add Cloud Account"}
        open={drawerOpen}
        onClose={() => setDrawerOpen(false)}
        width={720}
        destroyOnClose
        footer={
          <Space style={{ float: "right" }}>
            <Button onClick={() => setDrawerOpen(false)}>Cancel</Button>
            <Button type="primary" onClick={handleDrawerSubmit} loading={loading}>
              Save
            </Button>
          </Space>
        }
      >
        <Form layout="vertical" form={form}>
          <Form.Item name="name" label="Name" rules={[{ required: true }]}>
            <Input id="cloud-account-name" name="name" />
          </Form.Item>
          <Form.Item name="provider" label="Provider" rules={[{ required: true }]}>
            <Select id="cloud-account-provider">
              {providerOptions.map((option) => (
                <Option key={option} value={option}>
                  {option.toUpperCase()}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="external_id" label="External ID" rules={[{ required: true }]}>
            <Input id="cloud-account-external-id" name="external_id" />
          </Form.Item>
          <Form.Item name="status" label="Status" rules={[{ required: true }]}>
            <Select id="cloud-account-status">
              <Option value="active">Active</Option>
              <Option value="inactive">Inactive</Option>
            </Select>
          </Form.Item>

          {provider === "aws" && (
            <Space direction="vertical" size={16} style={{ width: "100%" }}>
              <Alert
                type="info"
                showIcon
                message="Blank throttling fields inherit the global CAASM defaults."
                description="Role ARN and base region remain required for AWS accounts. Use the account-level overrides only when this AWS account needs stricter limits or scoped regions. Account overrides can only narrow the global defaults and manual syncs still pass through runtime queue guards."
              />

              <Alert
                type="warning"
                showIcon
                message="Runtime and worker guardrails still apply"
                description="Saving a stricter account override does not bypass the shared runtime cap. If the worker pool is stopped or the runtime is already at pressure capacity, manual syncs for this account may be queued or deferred until capacity is available."
              />

              {(editing?.effective_throttling || editing?.throttling_contract) && (
                <Card size="small" title="Resolved throttling summary" bordered>
                  <Space direction="vertical" size={12} style={{ width: "100%" }}>
                    {editing?.effective_throttling && (
                      <Descriptions size="small" column={2} title="Effective throttling">
                        <Descriptions.Item label="Enabled">
                          {renderEffectiveThrottlingValue(editing.effective_throttling.enabled)}
                        </Descriptions.Item>
                        <Descriptions.Item label="Token capacity">
                          {renderEffectiveThrottlingValue(editing.effective_throttling.token_capacity)}
                        </Descriptions.Item>
                        <Descriptions.Item label="Refill / sec">
                          {renderEffectiveThrottlingValue(editing.effective_throttling.token_refill_per_sec)}
                        </Descriptions.Item>
                        <Descriptions.Item label="Adaptive threshold">
                          {renderEffectiveThrottlingValue(editing.effective_throttling.adaptive_threshold)}
                        </Descriptions.Item>
                        <Descriptions.Item label="Adaptive window (sec)">
                          {renderEffectiveThrottlingValue(editing.effective_throttling.adaptive_window_sec)}
                        </Descriptions.Item>
                        <Descriptions.Item label="Cool-off (sec)">
                          {renderEffectiveThrottlingValue(editing.effective_throttling.cool_off_sec)}
                        </Descriptions.Item>
                        <Descriptions.Item label="Max concurrency">
                          {renderEffectiveThrottlingValue(editing.effective_throttling.max_concurrency)}
                        </Descriptions.Item>
                        <Descriptions.Item label="Min concurrency">
                          {renderEffectiveThrottlingValue(editing.effective_throttling.min_concurrency)}
                        </Descriptions.Item>
                      </Descriptions>
                    )}

                    {editing?.throttling_contract && (
                      <Descriptions size="small" column={2} title="Throttling contract">
                        <Descriptions.Item label="Reject out of range">
                          {renderContractHardCapValue(editing.throttling_contract.reject_out_of_range)}
                        </Descriptions.Item>
                        <Descriptions.Item label="Override policy">
                          {renderContractHardCapValue(editing.throttling_contract.override_policy)}
                        </Descriptions.Item>
                        <Descriptions.Item label="Coordination mode">
                          {renderContractHardCapValue(editing.throttling_contract.coordination_mode)}
                        </Descriptions.Item>
                        <Descriptions.Item label="Supported services">
                          {renderContractHardCapValue(editing.throttling_contract.supported_services)}
                        </Descriptions.Item>
                        <Descriptions.Item label="Hard cap token capacity">
                          {renderContractHardCapValue(editing.throttling_contract.hard_caps?.token_capacity)}
                        </Descriptions.Item>
                        <Descriptions.Item label="Hard cap refill / sec">
                          {renderContractHardCapValue(editing.throttling_contract.hard_caps?.token_refill_per_sec)}
                        </Descriptions.Item>
                        <Descriptions.Item label="Hard cap max concurrency">
                          {renderContractHardCapValue(editing.throttling_contract.hard_caps?.max_concurrency)}
                        </Descriptions.Item>
                        <Descriptions.Item label="Hard cap min concurrency">
                          {renderContractHardCapValue(editing.throttling_contract.hard_caps?.min_concurrency)}
                        </Descriptions.Item>
                      </Descriptions>
                    )}
                  </Space>
                </Card>
              )}

              <Card size="small" title="AWS throttling overrides" bordered>
                <Space direction="vertical" size={12} style={{ width: "100%" }}>
                  <Row gutter={16}>
                    <Col span={12}>
                      <Form.Item
                        name="aws_role_arn"
                        label="Role ARN"
                        rules={[{ required: true, message: "Role ARN is required for AWS accounts" }]}
                        tooltip="IAM role ARN used by the collector to assume into this AWS account."
                      >
                        <Input id="cloud-account-aws-role-arn" name="aws_role_arn" placeholder="arn:aws:iam::123456789012:role/caasm-collector-role" />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        name="aws_region"
                        label="Base region"
                        rules={[{ required: true, message: "Base region is required for AWS accounts" }]}
                        tooltip="The primary AWS region used for credential validation and collector bootstrap."
                      >
                        <Input id="cloud-account-aws-region" name="aws_region" placeholder="us-east-1" />
                      </Form.Item>
                    </Col>
                  </Row>

                  <Form.Item
                    name="aws_allowed_regions"
                    label="Allowed regions override"
                    tooltip="Leave blank to inherit the global region scope."
                  >
                    <Select
                      id="cloud-account-aws-allowed-regions"
                      mode="tags"
                      placeholder="Enter AWS regions like us-east-1, eu-west-1"
                      tokenSeparators={[",", " "]}
                      style={{ width: "100%" }}
                    />
                  </Form.Item>

                  <Form.Item
                    name="aws_throttle_enabled"
                    label="Throttle enabled override"
                    tooltip="Inherit keeps the global setting. Enabled/Disabled overrides it for this account."
                  >
                    <Select
                      id="cloud-account-aws-throttle-enabled"
                      options={[
                        { value: "inherit", label: "Inherit global setting" },
                        { value: "enabled", label: "Enabled" },
                        { value: "disabled", label: "Disabled" },
                      ]}
                    />
                  </Form.Item>

                  <Row gutter={16}>
                    <Col span={12}>
                      <Form.Item
                        name="aws_throttle_tokens"
                        label="Token capacity override"
                        tooltip="Leave blank to inherit the global token capacity."
                      >
                        <InputNumber id="cloud-account-aws-throttle-tokens" name="aws_throttle_tokens" min={0} style={{ width: "100%" }} placeholder="Inherit" />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        name="aws_throttle_refill_per_sec"
                        label="Refill / sec override"
                        tooltip="Leave blank to inherit the global refill rate."
                      >
                        <InputNumber
                          id="cloud-account-aws-throttle-refill"
                          name="aws_throttle_refill_per_sec"
                          min={0}
                          step={0.5}
                          style={{ width: "100%" }}
                          placeholder="Inherit"
                        />
                      </Form.Item>
                    </Col>
                  </Row>

                  <Row gutter={16}>
                    <Col span={12}>
                      <Form.Item
                        name="aws_throttle_max_concurrency"
                        label="Max concurrency override"
                        tooltip="Leave blank to inherit the global max concurrency."
                      >
                        <InputNumber id="cloud-account-aws-throttle-max" name="aws_throttle_max_concurrency" min={1} style={{ width: "100%" }} placeholder="Inherit" />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        name="aws_throttle_min_concurrency"
                        label="Min concurrency override"
                        tooltip="Leave blank to inherit the global min concurrency."
                      >
                        <InputNumber id="cloud-account-aws-throttle-min" name="aws_throttle_min_concurrency" min={1} style={{ width: "100%" }} placeholder="Inherit" />
                      </Form.Item>
                    </Col>
                  </Row>
                </Space>
              </Card>

              <Collapse size="small" ghost>
                <Panel header="Advanced metadata fallback" key="advanced-metadata">
                  <Alert
                    type="warning"
                    showIcon
                    message="Use only for metadata without a dedicated field."
                    description="Role ARN, region, allowed regions, and throttling fields above are the primary source of truth. Extra metadata entered here is preserved, but matching AWS throttling keys are overwritten by the structured fields."
                    style={{ marginBottom: 12 }}
                  />
              <Form.Item name="metadata" label="Metadata (JSON)">
                <Input.TextArea id="cloud-account-metadata" name="metadata" rows={8} />
              </Form.Item>
            </Panel>
          </Collapse>
        </Space>
      )}

          {provider && provider !== "aws" && (
            <Form.Item name="metadata" label="Metadata (JSON)">
              <Input.TextArea id="cloud-account-metadata-generic" name="metadata" rows={8} />
            </Form.Item>
          )}
        </Form>
      </Drawer>

      <Modal
        title={`Jobs${selectedAccount ? ` - ${selectedAccount.name}` : ""}`}
        open={jobsModalOpen}
        onCancel={() => setJobsModalOpen(false)}
        footer={null}
        width={900}
      >
        <Table
          rowKey="id"
          loading={jobsLoading}
          dataSource={jobRecords}
          pagination={jobsPagination}
          onChange={(p) => {
            const accountId = selectedAccount?.id;
            if (!accountId) return;
            loadJobs(accountId, p.current ?? 1, p.pageSize ?? 10);
          }}
          columns={[
            { title: "Job ID", dataIndex: "id" },
            {
              title: "Status",
              dataIndex: "status",
              render: (value: string) => (
                <Tag color={value === "success" ? "green" : value === "failed" ? "red" : "default"}>{value}</Tag>
              ),
            },
            { title: "Started", dataIndex: "created_at" },
            {
              title: "Metadata",
              dataIndex: "metadata",
              render: (value: Record<string, unknown> | undefined) => <Text type="secondary">{value ? JSON.stringify(value) : "—"}</Text>,
            },
          ]}
        />
      </Modal>
    </Space>
  );
}
