"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import {
  Alert,
  Button,
  Card,
  Col,
  Descriptions,
  Drawer,
  Form,
  Input,
  Row,
  Select,
  Space,
  Statistic,
  Table,
  Tabs,
  Tag,
  Typography,
  message,
} from "antd";
import type { ColumnsType, TablePaginationConfig } from "antd/es/table";
import {
  CheckCircleOutlined,
  ReloadOutlined,
  SaveOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import dayjs from "dayjs";

import {
  fetchCaasmAPIRouteActiveConfig,
  fetchCaasmAPIRouteAssets,
  previewCaasmAPIRouteConfig,
  saveCaasmAPIRouteConfig,
} from "@/lib/api/caasm";
import { useAuth } from "@/lib/hooks/use-auth";
import type {
  CaasmAPIRouteAssetListParams,
  CaasmAPIRouteAssetRecord,
  CaasmAPIRouteConfigPreviewResult,
  CaasmAPIRouteConfigSummary,
} from "@/types/models";

const { Title, Paragraph, Text } = Typography;
const { TextArea } = Input;

type FilterState = {
  q: string;
  environment?: string;
  domain?: string;
  namespace?: string;
  service_name?: string;
  plugin?: string;
  route_kind?: string;
  external?: boolean;
};

type SelectOption = {
  label: string;
  value: string;
};

const routeKindOptions: SelectOption[] = [
  { label: "Test case", value: "test_case" },
  { label: "Regex", value: "regex" },
];

const externalOptions = [
  { label: "External", value: true },
  { label: "Internal", value: false },
];

const API_ROUTE_TABLE_SCROLL_X = 1630;
const CONFIG_PREVIEW_TABLE_SCROLL_X = 1220;

function formatDate(value?: string | null) {
  return value ? dayjs(value).format("YYYY-MM-DD HH:mm") : "—";
}

function formatBoolean(value?: boolean) {
  return value ? "Yes" : "No";
}

function normalizeEnvironmentOptions(records: CaasmAPIRouteAssetRecord[]) {
  const environments = new Set<string>();
  records.forEach((record) => {
    Object.keys(record.domains || {}).forEach((environment) => {
      if (environment) {
        environments.add(environment);
      }
    });
    Object.keys(record.namespace_map || {}).forEach((environment) => {
      if (environment) {
        environments.add(environment);
      }
    });
  });
  return Array.from(environments)
    .sort()
    .map((environment) => ({ label: environment, value: environment }));
}

function pickEnvironmentValue(
  values: Record<string, string[] | string> | undefined,
  environment?: string,
) {
  if (!values) {
    return "—";
  }

  if (environment && values[environment]) {
    const scopedValue = values[environment];
    return Array.isArray(scopedValue) ? scopedValue.join(", ") : scopedValue;
  }

  if (values.prod) {
    const prodValue = values.prod;
    return Array.isArray(prodValue) ? prodValue.join(", ") : prodValue;
  }

  const firstKey = Object.keys(values)[0];
  if (!firstKey) {
    return "—";
  }

  const firstValue = values[firstKey];
  return Array.isArray(firstValue) ? firstValue.join(", ") : firstValue;
}

function renderPluginTags(plugins?: string[], maxVisible = 3) {
  const visible = (plugins || []).slice(0, maxVisible);
  const overflow = Math.max((plugins || []).length - visible.length, 0);

  if (visible.length === 0) {
    return <Text type="secondary">—</Text>;
  }

  return (
    <div
      style={{
        display: "flex",
        flexWrap: "wrap",
        gap: 4,
        maxWidth: "100%",
        minWidth: 0,
        overflow: "hidden",
      }}
    >
      {visible.map((plugin) => (
        <Tag
          key={plugin}
          title={plugin}
          style={{
            display: "inline-block",
            maxWidth: "100%",
            minWidth: 0,
            marginInlineEnd: 0,
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap",
          }}
        >
          {plugin}
        </Tag>
      ))}
      {overflow > 0 ? (
        <Tag style={{ marginInlineEnd: 0 }}>+{overflow}</Tag>
      ) : null}
    </div>
  );
}

function previewItems(preview?: CaasmAPIRouteConfigPreviewResult | null) {
  return preview?.preview || preview?.preview_items || preview?.items || preview?.routes || [];
}

function JsonBlock({ value }: { value: unknown }) {
  return (
    <pre
      style={{
        margin: 0,
        whiteSpace: "pre-wrap",
        wordBreak: "break-word",
        fontSize: 12,
      }}
    >
      {JSON.stringify(value ?? {}, null, 2)}
    </pre>
  );
}

function RouteDetailDrawer({
  record,
  open,
  onClose,
}: {
  record: CaasmAPIRouteAssetRecord | null;
  open: boolean;
  onClose: () => void;
}) {
  return (
    <Drawer
      title={record?.route_path || "API gateway route detail"}
      open={open}
      onClose={onClose}
      width={760}
    >
      {record ? (
        <Space direction="vertical" size={16} style={{ width: "100%" }}>
          <Descriptions size="small" column={1} bordered title="Basic">
            <Descriptions.Item label="ID">{record.id}</Descriptions.Item>
            <Descriptions.Item label="Config ID">
              {record.config_id}
            </Descriptions.Item>
            <Descriptions.Item label="Route kind">
              <Tag color={record.route_kind === "regex" ? "purple" : "blue"}>
                {record.route_kind}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="Route path">
              <Text copyable>{record.route_path}</Text>
            </Descriptions.Item>
            <Descriptions.Item label="Route key">
              <Text copyable>{record.route_key}</Text>
            </Descriptions.Item>
            <Descriptions.Item label="Occurrences">
              {record.occurrence_count}
            </Descriptions.Item>
          </Descriptions>

          <Descriptions size="small" column={2} bordered title="YAML Source">
            <Descriptions.Item label="Group index">
              {record.group_index}
            </Descriptions.Item>
            <Descriptions.Item label="Ingress index">
              {record.ingress_index}
            </Descriptions.Item>
            <Descriptions.Item label="Service index">
              {record.service_index}
            </Descriptions.Item>
            <Descriptions.Item label="Route index">
              {record.route_index}
            </Descriptions.Item>
          </Descriptions>

          <Descriptions size="small" column={1} bordered title="Domains and Namespace">
            <Descriptions.Item label="Domains">
              <JsonBlock value={record.domains} />
            </Descriptions.Item>
            <Descriptions.Item label="Namespace map">
              <JsonBlock value={record.namespace_map} />
            </Descriptions.Item>
          </Descriptions>

          <Descriptions size="small" column={1} bordered title="Ingress and Service">
            <Descriptions.Item label="Ingress prefix">
              {record.ingress_name_prefix || "—"}
            </Descriptions.Item>
            <Descriptions.Item label="External">
              {formatBoolean(record.external)}
            </Descriptions.Item>
            <Descriptions.Item label="Strip path">
              {formatBoolean(record.strip_path)}
            </Descriptions.Item>
            <Descriptions.Item label="Service name">
              {record.service_name || "—"}
            </Descriptions.Item>
            <Descriptions.Item label="Service port">
              {record.service_port ?? "—"}
            </Descriptions.Item>
          </Descriptions>

          <Descriptions size="small" column={1} bordered title="Plugins">
            <Descriptions.Item label="Parsed plugins">
              {renderPluginTags(record.plugins, record.plugins?.length || 0)}
            </Descriptions.Item>
            <Descriptions.Item label="Raw plugins">
              {record.raw_plugins || "—"}
            </Descriptions.Item>
          </Descriptions>

          <Descriptions size="small" column={1} bordered title="Source Config">
            <Descriptions.Item label="Config name">
              {record.config?.name || "—"}
            </Descriptions.Item>
            <Descriptions.Item label="Activated at">
              {formatDate(record.config?.activated_at)}
            </Descriptions.Item>
            <Descriptions.Item label="Uploaded by">
              {record.config?.uploaded_by_name || record.config?.uploaded_by || "—"}
            </Descriptions.Item>
          </Descriptions>

          <Descriptions size="small" column={1} bordered title="Timestamps">
            <Descriptions.Item label="Created at">
              {formatDate(record.created_at)}
            </Descriptions.Item>
            <Descriptions.Item label="Updated at">
              {formatDate(record.updated_at)}
            </Descriptions.Item>
            <Descriptions.Item label="Deleted at">
              {formatDate(record.deleted_at)}
            </Descriptions.Item>
          </Descriptions>
        </Space>
      ) : (
        <Paragraph type="secondary">Select a route to view details.</Paragraph>
      )}
    </Drawer>
  );
}

function APIAssetsTab() {
  const [records, setRecords] = useState<CaasmAPIRouteAssetRecord[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [filters, setFilters] = useState<FilterState>({ q: "" });
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 20,
  });
  const [selectedRecord, setSelectedRecord] =
    useState<CaasmAPIRouteAssetRecord | null>(null);

  const environmentOptions = useMemo(
    () => normalizeEnvironmentOptions(records),
    [records],
  );
  const currentPage = pagination.current ?? 1;
  const currentPageSize = pagination.pageSize ?? 20;

  const loadData = useCallback(
    async (page: number, pageSize: number) => {
      setLoading(true);
      try {
        const params: CaasmAPIRouteAssetListParams = {
          page,
          page_size: pageSize,
          q: filters.q || undefined,
          environment: filters.environment,
          domain: filters.domain,
          namespace: filters.namespace,
          service_name: filters.service_name,
          plugin: filters.plugin,
          route_kind: filters.route_kind,
          external: filters.external,
        };
        const payload = await fetchCaasmAPIRouteAssets(params);
        setRecords(payload.items || []);
        setTotal(payload.total || 0);
      } catch (error) {
        console.error("Failed to load CAASM API gateway routes", error);
        message.error("Failed to load API gateway routes");
      } finally {
        setLoading(false);
      }
    },
    [filters],
  );

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

  const handleFilterChange = (
    field: keyof Omit<FilterState, "external">,
    value?: string,
  ) => {
    setFilters((previous) => ({ ...previous, [field]: value || undefined }));
    setPagination((previous) => ({ ...previous, current: 1 }));
  };

  const handleExternalChange = (value?: boolean) => {
    setFilters((previous) => ({ ...previous, external: value }));
    setPagination((previous) => ({ ...previous, current: 1 }));
  };

  const resetFilters = () => {
    setFilters({ q: "" });
    setPagination((previous) => ({ ...previous, current: 1 }));
  };

  const columns: ColumnsType<CaasmAPIRouteAssetRecord> = useMemo(
    () => [
      {
        title: "Route path",
        dataIndex: "route_path",
        width: 280,
        render: (value: string, record) => (
          <Button
            type="link"
            onClick={() => setSelectedRecord(record)}
            style={{
              maxWidth: "100%",
              padding: 0,
              height: "auto",
              textAlign: "left",
              whiteSpace: "normal",
              wordBreak: "break-word",
            }}
          >
            {value}
          </Button>
        ),
      },
      {
        title: "Kind",
        dataIndex: "route_kind",
        width: 120,
        render: (value: string) => (
          <Tag color={value === "regex" ? "purple" : "blue"}>{value}</Tag>
        ),
      },
      {
        title: "Service",
        dataIndex: "service_name",
        width: 180,
        render: (value: string) => (
          <Text ellipsis={{ tooltip: value }} style={{ maxWidth: 160 }}>
            {value || "—"}
          </Text>
        ),
      },
      {
        title: "Port",
        dataIndex: "service_port",
        width: 90,
        render: (value?: number | null) => value ?? "—",
      },
      {
        title: "Domain",
        dataIndex: "domains",
        width: 220,
        render: (_, record) => (
          <Text
            ellipsis={{
              tooltip: pickEnvironmentValue(record.domains, filters.environment),
            }}
            style={{ maxWidth: 200 }}
          >
            {pickEnvironmentValue(record.domains, filters.environment)}
          </Text>
        ),
      },
      {
        title: "Namespace",
        dataIndex: "namespace_map",
        width: 180,
        render: (_, record) => (
          <Text
            ellipsis={{
              tooltip: pickEnvironmentValue(
                record.namespace_map,
                filters.environment,
              ),
            }}
            style={{ maxWidth: 160 }}
          >
            {pickEnvironmentValue(record.namespace_map, filters.environment)}
          </Text>
        ),
      },
      {
        title: "Plugins",
        dataIndex: "plugins",
        width: 220,
        render: (plugins: string[]) => renderPluginTags(plugins),
      },
      {
        title: "External",
        dataIndex: "external",
        width: 100,
        render: (value: boolean) => (
          <Tag color={value ? "orange" : "green"}>{formatBoolean(value)}</Tag>
        ),
      },
      {
        title: "Count",
        dataIndex: "occurrence_count",
        width: 90,
      },
      {
        title: "Updated",
        dataIndex: "updated_at",
        width: 150,
        render: (value: string | undefined, record) =>
          formatDate(value || record.config?.activated_at),
      },
    ],
    [filters.environment],
  );

  return (
    <Space direction="vertical" size={16} style={{ width: "100%" }}>
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={18}>
          <Card>
            <Space direction="vertical" size={16} style={{ width: "100%" }}>
              <div
                style={{
                  display: "flex",
                  justifyContent: "space-between",
                  gap: 16,
                  alignItems: "flex-start",
                }}
              >
                <div>
                  <Title level={4} style={{ margin: 0 }}>
                    API gateway route inventory
                  </Title>
                  <Paragraph type="secondary" style={{ marginBottom: 0 }}>
                    Kong YAML routes parsed into queryable CAASM gateway routes.
                  </Paragraph>
                </div>
                <Button
                  icon={<ReloadOutlined />}
                  onClick={() =>
                    loadData(pagination.current ?? 1, pagination.pageSize ?? 20)
                  }
                >
                  Refresh
                </Button>
              </div>

              <Form layout="vertical">
                <Row gutter={16}>
                  <Col xs={24} md={8}>
                    <Form.Item label="Search">
                      <Input
                        prefix={<SearchOutlined />}
                        placeholder="Route, service, domain"
                        allowClear
                        value={filters.q}
                        onChange={(event) =>
                          handleFilterChange("q", event.target.value)
                        }
                      />
                    </Form.Item>
                  </Col>
                  <Col xs={24} md={4}>
                    <Form.Item label="Environment">
                      <Select
                        allowClear
                        options={environmentOptions}
                        value={filters.environment}
                        onChange={(value) =>
                          handleFilterChange("environment", value)
                        }
                      />
                    </Form.Item>
                  </Col>
                  <Col xs={24} md={4}>
                    <Form.Item label="Kind">
                      <Select
                        allowClear
                        options={routeKindOptions}
                        value={filters.route_kind}
                        onChange={(value) =>
                          handleFilterChange("route_kind", value)
                        }
                      />
                    </Form.Item>
                  </Col>
                  <Col xs={24} md={4}>
                    <Form.Item label="External">
                      <Select
                        allowClear
                        options={externalOptions}
                        value={filters.external}
                        onChange={handleExternalChange}
                      />
                    </Form.Item>
                  </Col>
                  <Col xs={24} md={4}>
                    <Form.Item label="Plugin">
                      <Input
                        allowClear
                        value={filters.plugin}
                        onChange={(event) =>
                          handleFilterChange("plugin", event.target.value)
                        }
                      />
                    </Form.Item>
                  </Col>
                  <Col xs={24} md={6}>
                    <Form.Item label="Domain">
                      <Input
                        allowClear
                        value={filters.domain}
                        onChange={(event) =>
                          handleFilterChange("domain", event.target.value)
                        }
                      />
                    </Form.Item>
                  </Col>
                  <Col xs={24} md={6}>
                    <Form.Item label="Namespace">
                      <Input
                        allowClear
                        value={filters.namespace}
                        onChange={(event) =>
                          handleFilterChange("namespace", event.target.value)
                        }
                      />
                    </Form.Item>
                  </Col>
                  <Col xs={24} md={6}>
                    <Form.Item label="Service">
                      <Input
                        allowClear
                        value={filters.service_name}
                        onChange={(event) =>
                          handleFilterChange("service_name", event.target.value)
                        }
                      />
                    </Form.Item>
                  </Col>
                  <Col xs={24} md={6}>
                    <Form.Item label=" ">
                      <Button type="link" onClick={resetFilters}>
                        Reset filters
                      </Button>
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
            </Space>
          </Card>
        </Col>
        <Col xs={24} lg={6}>
          <Card>
            <Statistic title="Gateway routes" value={total} />
          </Card>
        </Col>
      </Row>

      <Card>
        <Table
          rowKey="id"
          loading={loading}
          dataSource={records}
          columns={columns}
          tableLayout="fixed"
          scroll={{ x: API_ROUTE_TABLE_SCROLL_X }}
          pagination={{ ...pagination, total }}
          onChange={(nextPagination) => setPagination(nextPagination)}
        />
      </Card>

      <RouteDetailDrawer
        record={selectedRecord}
        open={Boolean(selectedRecord)}
        onClose={() => setSelectedRecord(null)}
      />
    </Space>
  );
}

function ConfigTab({ onSaved }: { onSaved: () => void }) {
  const [name, setName] = useState("");
  const [rawYaml, setRawYaml] = useState("");
  const [activeConfig, setActiveConfig] =
    useState<CaasmAPIRouteConfigSummary | null>(null);
  const [configLoading, setConfigLoading] = useState(false);
  const [preview, setPreview] =
    useState<CaasmAPIRouteConfigPreviewResult | null>(null);
  const [parseError, setParseError] = useState<string | null>(null);
  const [previewLoading, setPreviewLoading] = useState(false);
  const [saving, setSaving] = useState(false);

  const loadActiveConfig = useCallback(async () => {
    setConfigLoading(true);
    try {
      setActiveConfig(await fetchCaasmAPIRouteActiveConfig());
    } catch (error) {
      console.error("Failed to load active API route config", error);
      message.error("Failed to load active config");
    } finally {
      setConfigLoading(false);
    }
  }, []);

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

  const runPreview = async () => {
    if (!rawYaml.trim()) {
      setParseError("YAML content is required.");
      setPreview(null);
      return;
    }

    setPreviewLoading(true);
    setParseError(null);
    try {
      const result = await previewCaasmAPIRouteConfig({
        name: name.trim() || undefined,
        raw_yaml: rawYaml,
      });
      const nextError = result.error_message || result.error || null;
      setPreview(result);
      setParseError(nextError);
      if (!nextError) {
        message.success("Preview parsed successfully");
      }
    } catch (error: any) {
      const errorMessage =
        error?.response?.data?.message ||
        error?.response?.data?.data?.error_message ||
        error?.message ||
        "Failed to preview YAML";
      setPreview(null);
      setParseError(errorMessage);
    } finally {
      setPreviewLoading(false);
    }
  };

  const saveActive = async () => {
    if (!rawYaml.trim()) {
      setParseError("YAML content is required.");
      return;
    }

    setSaving(true);
    setParseError(null);
    try {
      const savedConfig = await saveCaasmAPIRouteConfig({
        name: name.trim() || undefined,
        raw_yaml: rawYaml,
      });
      setActiveConfig(savedConfig);
      setPreview(null);
      message.success("API gateway route configuration activated");
      onSaved();
    } catch (error: any) {
      const errorMessage =
        error?.response?.data?.message ||
        error?.response?.data?.data?.error_message ||
        error?.message ||
        "Failed to save configuration";
      setParseError(errorMessage);
    } finally {
      setSaving(false);
    }
  };

  const canSave =
    rawYaml.trim().length > 0 &&
    Boolean(preview) &&
    !parseError &&
    !previewLoading &&
    !saving;

  const previewColumns: ColumnsType<CaasmAPIRouteAssetRecord> = [
    {
      title: "Route path",
      dataIndex: "route_path",
      width: 260,
      render: (value: string) => (
        <Text ellipsis={{ tooltip: value }} style={{ maxWidth: 240 }}>
          {value}
        </Text>
      ),
    },
    {
      title: "Kind",
      dataIndex: "route_kind",
      width: 110,
      render: (value: string) => (
        <Tag color={value === "regex" ? "purple" : "blue"}>{value}</Tag>
      ),
    },
    {
      title: "Service",
      dataIndex: "service_name",
      width: 170,
    },
    {
      title: "Port",
      dataIndex: "service_port",
      width: 80,
      render: (value?: number | null) => value ?? "—",
    },
    {
      title: "Domain",
      dataIndex: "domains",
      width: 220,
      render: (_, record) => pickEnvironmentValue(record.domains),
    },
    {
      title: "Namespace",
      dataIndex: "namespace_map",
      width: 160,
      render: (_, record) => pickEnvironmentValue(record.namespace_map),
    },
    {
      title: "Plugins",
      dataIndex: "plugins",
      width: 200,
      render: (plugins: string[]) => renderPluginTags(plugins),
    },
  ];

  return (
    <Space direction="vertical" size={16} style={{ width: "100%" }}>
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={16}>
          <Card>
            <Space direction="vertical" size={16} style={{ width: "100%" }}>
              <div>
                <Title level={4} style={{ margin: 0 }}>
                  Kong YAML configuration
                </Title>
                <Paragraph type="secondary" style={{ marginBottom: 0 }}>
                  Paste a full Kong route YAML snapshot, preview parsed gateway routes, then save it as the active configuration.
                </Paragraph>
              </div>
              <Form layout="vertical">
                <Form.Item label="Config name">
                  <Input
                    value={name}
                    onChange={(event) => setName(event.target.value)}
                    placeholder="Kong route config"
                    maxLength={255}
                  />
                </Form.Item>
                <Form.Item label="YAML">
                  <TextArea
                    value={rawYaml}
                    onChange={(event) => {
                      setRawYaml(event.target.value);
                      setPreview(null);
                      setParseError(null);
                    }}
                    rows={18}
                    placeholder="- domains:&#10;    prod: [api.example.com]&#10;  ingressNamePrefix: api&#10;  ingresses: []"
                    style={{ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace" }}
                  />
                </Form.Item>
                {parseError ? (
                  <Alert
                    type="error"
                    showIcon
                    message="YAML parse error"
                    description={parseError}
                  />
                ) : null}
                <Space wrap>
                  <Button
                    icon={<SearchOutlined />}
                    onClick={runPreview}
                    loading={previewLoading}
                  >
                    Preview
                  </Button>
                  <Button
                    type="primary"
                    icon={<SaveOutlined />}
                    onClick={saveActive}
                    loading={saving}
                    disabled={!canSave}
                  >
                    Save active
                  </Button>
                </Space>
              </Form>
            </Space>
          </Card>
        </Col>
        <Col xs={24} lg={8}>
          <Card loading={configLoading} title="Active config">
            {activeConfig ? (
              <Descriptions size="small" column={1}>
                <Descriptions.Item label="Name">
                  {activeConfig.name}
                </Descriptions.Item>
                <Descriptions.Item label="Status">
                  <Tag color={activeConfig.status === "active" ? "green" : "default"}>
                    {activeConfig.status}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="Routes">
                  {activeConfig.route_count}
                </Descriptions.Item>
                <Descriptions.Item label="Activated">
                  {formatDate(activeConfig.activated_at)}
                </Descriptions.Item>
                <Descriptions.Item label="Uploaded by">
                  {activeConfig.uploaded_by_name || activeConfig.uploaded_by || "—"}
                </Descriptions.Item>
                <Descriptions.Item label="SHA256">
                  <Text copyable ellipsis={{ tooltip: activeConfig.yaml_sha256 }}>
                    {activeConfig.yaml_sha256 || "—"}
                  </Text>
                </Descriptions.Item>
              </Descriptions>
            ) : (
              <Paragraph type="secondary" style={{ marginBottom: 0 }}>
                No active API gateway route configuration.
              </Paragraph>
            )}
          </Card>
        </Col>
      </Row>

      <Card
        title="Preview"
        extra={
          preview && !parseError ? (
            <Space>
              <CheckCircleOutlined style={{ color: "#16a34a" }} />
              <Text>{preview.route_count} routes parsed</Text>
            </Space>
          ) : null
        }
      >
        <Table
          rowKey={(record) => record.route_key || `${record.service_name}-${record.route_path}`}
          dataSource={previewItems(preview)}
          columns={previewColumns}
          tableLayout="fixed"
          scroll={{ x: CONFIG_PREVIEW_TABLE_SCROLL_X }}
          pagination={{ pageSize: 10 }}
        />
      </Card>
    </Space>
  );
}

export default function CaasmAPIAssetsPage() {
  const { hasPermission } = useAuth();
  const canManageAPIAssets = hasPermission("caasm:manage_api_assets");
  const [activeTab, setActiveTab] = useState("assets");
  const [refreshToken, setRefreshToken] = useState(0);

  useEffect(() => {
    if (!canManageAPIAssets && activeTab === "config") {
      setActiveTab("assets");
    }
  }, [activeTab, canManageAPIAssets]);

  const tabItems = [
    {
      key: "assets",
      label: "API Gateway Routes",
      children: <APIAssetsTab key={refreshToken} />,
    },
    ...(canManageAPIAssets
      ? [
          {
            key: "config",
            label: "Configuration",
            children: (
              <ConfigTab onSaved={() => setRefreshToken((value) => value + 1)} />
            ),
          },
        ]
      : []),
  ];

  return (
    <Space direction="vertical" size={24} style={{ width: "100%" }}>
      <div>
        <Title level={3} style={{ marginBottom: 4 }}>
          API Assets
        </Title>
        <Paragraph type="secondary" style={{ marginBottom: 0 }}>
          Kong route configuration parsed into CAASM API gateway route inventory.
        </Paragraph>
      </div>

      {!canManageAPIAssets ? (
        <Alert
          type="info"
          showIcon
          message="Configuration controls are hidden for this account."
        />
      ) : null}

      <Tabs activeKey={activeTab} onChange={setActiveTab} items={tabItems} />
    </Space>
  );
}
