"use client";

import { PlusOutlined } from "@ant-design/icons";
import {
  Badge,
  Button,
  Card,
  Checkbox,
  Col,
  Form,
  Input,
  List,
  Modal,
  Row,
  Select,
  Space,
  Spin,
  Statistic,
  Switch,
  Table,
  Tabs,
  Tag,
  Typography,
  message,
  type TablePaginationConfig,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import { useCallback, useEffect, useMemo, useState } from "react";

import {
  fetchVulnerabilityConfig,
  updateVulnerabilitySLA,
  updateVulnerabilitySubmissionRequirements,
  type VulnerabilityConfig,
} from "@/lib/api/vulnerability-config";
import {
  createVulnerabilityTag,
  deleteVulnerabilityTag,
  fetchVulnerabilityTagStats,
  listVulnerabilityTags,
  updateVulnerabilityTag,
  type TagPayload,
  type VulnerabilityTag,
} from "@/lib/api/vulnerability-tags";
import {
  createDiscoveryChannel,
  deleteDiscoveryChannel,
  listDiscoveryChannels,
  updateDiscoveryChannel,
  type DiscoveryChannel,
  type DiscoveryChannelPayload,
} from "@/lib/api/vulnerability-discovery-channels";
import {
  createVulnerabilityType,
  deleteVulnerabilityType,
  listVulnerabilityTypes,
  updateVulnerabilityType,
  type VulnerabilityType,
  type VulnerabilityTypePayload,
} from "@/lib/api/vulnerability-types";
import {
  createVulnerabilitySource,
  deleteVulnerabilitySource,
  listVulnerabilitySources,
  updateVulnerabilitySource,
  type VulnerabilitySource,
  type VulnerabilitySourcePayload,
} from "@/lib/api/vulnerability-sources";
import { useAuth } from "@/lib/hooks/use-auth";

const { Title, Paragraph, Text } = Typography;

const SYSTEM_FILTER_OPTIONS = [
  { label: "All", value: "all" },
  { label: "System only", value: "system" },
  { label: "Custom only", value: "custom" },
];

const SUBMISSION_LOCKED_FIELDS = [
  "title",
  "severity_level",
  "discoverer_employee_id",
];

const SUBMISSION_RECOMMENDED_FIELDS = [
  ...SUBMISSION_LOCKED_FIELDS,
  "vulnerability_type",
  "application",
  "source",
  "discovery_phase",
  "network_env",
  "description",
];

const SUBMISSION_FIELD_GROUPS = [
  {
    title: "Core Details",
    description: "Fields reviewers need to identify and triage the finding.",
    fields: [
      { key: "title", label: "Title", help: "Short vulnerability summary." },
      { key: "severity_level", label: "Severity", help: "Risk level used for priority and SLA." },
      { key: "vulnerability_type", label: "Vulnerability Type", help: "Category used for reporting and routing." },
      { key: "affected_assets_count", label: "Affected Assets Count", help: "Number of known affected assets." },
    ],
  },
  {
    title: "Ownership and Scope",
    description: "People and systems involved in remediation.",
    fields: [
      { key: "discoverer_employee_id", label: "Discoverer", help: "Employee who found or submitted the issue." },
      { key: "fixer_employee_id", label: "Fixer", help: "Employee expected to remediate the issue." },
      { key: "owner_employee_id", label: "Owner", help: "Accountable owner for the finding." },
      { key: "department_id", label: "Department", help: "Responsible organization or business unit." },
      { key: "application", label: "Application/System", help: "Affected application, service, or system." },
      { key: "code_repository", label: "Code Repository", help: "Repository linked to the vulnerable code." },
    ],
  },
  {
    title: "Discovery Context",
    description: "Where and how the issue was found.",
    fields: [
      { key: "source", label: "Source", help: "Standardized source such as scanner, manual review, or external report." },
      { key: "discovery_channel", label: "Discovery Channel", help: "Inbound channel or detection method." },
      { key: "discovery_phase", label: "Discovery Phase", help: "Lifecycle stage where the issue was observed." },
      { key: "network_env", label: "Network Environment", help: "Exposure context such as internal or external." },
      { key: "interface_path", label: "Interface Path", help: "Affected URL, API route, method, or admin path." },
    ],
  },
  {
    title: "Evidence and Triage",
    description: "Evidence required to reproduce, verify, and classify the finding.",
    fields: [
      { key: "description", label: "Description", help: "Rich-text report body." },
      { key: "verification_steps", label: "Verification Steps", help: "Steps used to reproduce or validate the issue." },
      { key: "poc_text", label: "Proof of Concept", help: "Proof-of-concept notes or payloads." },
      { key: "tags", label: "Tags", help: "Labels used for filtering and reporting." },
      { key: "dependency_name", label: "Dependency Name", help: "Third-party package, library, or vendor component." },
      { key: "dependency_version", label: "Dependency Version", help: "Affected dependency version." },
    ],
  },
];

const SUBMISSION_FIELD_ORDER = SUBMISSION_FIELD_GROUPS.flatMap((group) =>
  group.fields.map((field) => field.key),
);

function normalizeSubmissionFields(fields: string[]): string[] {
  const selected = new Set(fields);
  SUBMISSION_LOCKED_FIELDS.forEach((field) => selected.add(field));
  return SUBMISSION_FIELD_ORDER.filter((field) => selected.has(field));
}

export default function VulnerabilityConfigurationPage() {
  const { hasPermission } = useAuth();
  const canManage = hasPermission("vuln:manage_findings");

  const [activeTab, setActiveTab] = useState<string>("reference");

  const [config, setConfig] = useState<VulnerabilityConfig | null>(null);
  const [configLoading, setConfigLoading] = useState(true);

  const [tagLoading, setTagLoading] = useState(false);
  const [tagData, setTagData] = useState<VulnerabilityTag[]>([]);
  const [tagTotal, setTagTotal] = useState(0);
  const [tagPagination, setTagPagination] = useState<TablePaginationConfig>({ current: 1, pageSize: 20 });
  const [search, setSearch] = useState("");
  const [categoryFilter, setCategoryFilter] = useState<string | undefined>(undefined);
  const [systemFilter, setSystemFilter] = useState("all");
  const [tagStats, setTagStats] = useState<{ total: number; by_category: Record<string, number> } | null>({ total: 0, by_category: {} });
  const [modalOpen, setModalOpen] = useState(false);
  const [editingTag, setEditingTag] = useState<VulnerabilityTag | null>(null);
  const [form] = Form.useForm<TagPayload>();

  const [channelLoading, setChannelLoading] = useState(false);
  const [channelData, setChannelData] = useState<DiscoveryChannel[]>([]);
  const [channelTotal, setChannelTotal] = useState(0);
  const [channelPagination, setChannelPagination] = useState<TablePaginationConfig>({ current: 1, pageSize: 20 });
  const [channelSearch, setChannelSearch] = useState("");
  const [channelSystemFilter, setChannelSystemFilter] = useState("all");
  const [channelModalOpen, setChannelModalOpen] = useState(false);
  const [editingChannel, setEditingChannel] = useState<DiscoveryChannel | null>(null);
  const [channelForm] = Form.useForm<DiscoveryChannelPayload>();

  const [typeLoading, setTypeLoading] = useState(false);
  const [typeData, setTypeData] = useState<VulnerabilityType[]>([]);
  const [typeTotal, setTypeTotal] = useState(0);
  const [typePagination, setTypePagination] = useState<TablePaginationConfig>({ current: 1, pageSize: 20 });
  const [typeSearch, setTypeSearch] = useState("");
  const [typeCategoryFilter, setTypeCategoryFilter] = useState<string | undefined>(undefined);
  const [typeSeverityFilter, setTypeSeverityFilter] = useState<string | undefined>(undefined);
  const [typeSystemFilter, setTypeSystemFilter] = useState("all");
  const [typeModalOpen, setTypeModalOpen] = useState(false);
  const [editingType, setEditingType] = useState<VulnerabilityType | null>(null);
  const [typeForm] = Form.useForm<VulnerabilityTypePayload>();

  const [slaForm] = Form.useForm();
  const [savingSLA, setSavingSLA] = useState(false);
  const [submissionFields, setSubmissionFields] = useState<string[]>([]);
  const [savingSubmissionRequirements, setSavingSubmissionRequirements] = useState(false);

  const [sourceLoading, setSourceLoading] = useState(false);
  const [sourceData, setSourceData] = useState<VulnerabilitySource[]>([]);
  const [sourceTotal, setSourceTotal] = useState(0);
  const [sourcePagination, setSourcePagination] = useState<TablePaginationConfig>({ current: 1, pageSize: 20 });
  const [sourceSearch, setSourceSearch] = useState("");
  const [sourceSystemFilter, setSourceSystemFilter] = useState("all");
  const [sourceModalOpen, setSourceModalOpen] = useState(false);
  const [editingSource, setEditingSource] = useState<VulnerabilitySource | null>(null);
  const [sourceForm] = Form.useForm<VulnerabilitySourcePayload>();

  const loadConfig = useCallback(async () => {
    setConfigLoading(true);
    try {
      const data = await fetchVulnerabilityConfig();
      setConfig(data);
    } catch (error) {
      message.error("Failed to load configuration data");
    } finally {
      setConfigLoading(false);
    }
  }, []);

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

  useEffect(() => {
    if (config?.sla_rules) {
      slaForm.setFieldsValue({
        critical: config.sla_rules["critical"],
        high: config.sla_rules["high"],
        medium: config.sla_rules["medium"],
        low: config.sla_rules["low"],
      });
    }
  }, [config, slaForm]);

  useEffect(() => {
    setSubmissionFields(normalizeSubmissionFields(config?.submission_required_fields ?? SUBMISSION_RECOMMENDED_FIELDS));
  }, [config?.submission_required_fields]);

  const loadTags = useCallback(
    async (page: number, pageSize: number) => {
      if (activeTab !== "tags") return;
      setTagLoading(true);
      try {
        const payload = await listVulnerabilityTags({
          page,
          page_size: pageSize,
          q: search || undefined,
          category: categoryFilter || undefined,
          system_only: systemFilter === "system" ? true : systemFilter === "custom" ? false : undefined,
        });
        setTagData(payload.items ?? []);
        setTagTotal(payload.total ?? 0);
      } catch (error) {
        message.error("Failed to load tags");
      } finally {
        setTagLoading(false);
      }
    },
    [activeTab, categoryFilter, search, systemFilter],
  );

  const refreshTagStats = useCallback(async () => {
    if (activeTab !== "tags") return;
    try {
      const stats = await fetchVulnerabilityTagStats();
      setTagStats(stats);
    } catch (error) {
      console.error(error);
    }
  }, [activeTab]);

  const loadChannels = useCallback(
    async (page: number, pageSize: number) => {
      if (activeTab !== "channels") return;
      setChannelLoading(true);
      try {
        const payload = await listDiscoveryChannels({
          page,
          page_size: pageSize,
          q: channelSearch || undefined,
          system_only:
            channelSystemFilter === "system" ? true : channelSystemFilter === "custom" ? false : undefined,
        });
        setChannelData(payload.items ?? []);
        setChannelTotal(payload.total ?? 0);
      } catch (error) {
        message.error("Failed to load discovery channels");
      } finally {
        setChannelLoading(false);
      }
    },
    [activeTab, channelSearch, channelSystemFilter],
  );

  const loadTypes = useCallback(
    async (page: number, pageSize: number) => {
      if (activeTab !== "types") return;
      setTypeLoading(true);
      try {
        const payload = await listVulnerabilityTypes({
          page,
          page_size: pageSize,
          q: typeSearch || undefined,
          category: typeCategoryFilter || undefined,
          severity: typeSeverityFilter || undefined,
          system_only: typeSystemFilter === "system" ? true : typeSystemFilter === "custom" ? false : undefined,
        });
        setTypeData(payload.items ?? []);
        setTypeTotal(payload.total ?? 0);
      } catch (error) {
        message.error("Failed to load vulnerability types");
      } finally {
        setTypeLoading(false);
      }
    },
    [activeTab, typeCategoryFilter, typeSearch, typeSeverityFilter, typeSystemFilter],
  );

  const loadSources = useCallback(
    async (page: number, pageSize: number) => {
      if (activeTab !== "sources") return;
      setSourceLoading(true);
      try {
        const payload = await listVulnerabilitySources({
          page,
          page_size: pageSize,
          q: sourceSearch || undefined,
          system_only:
            sourceSystemFilter === "system" ? true : sourceSystemFilter === "custom" ? false : undefined,
        });
        setSourceData(payload.items ?? []);
        setSourceTotal(payload.total ?? 0);
      } catch (error) {
        message.error("Failed to load sources");
      } finally {
        setSourceLoading(false);
      }
    },
    [activeTab, sourceSearch, sourceSystemFilter],
  );

  useEffect(() => {
    if (activeTab !== "tags") return;
    const current = tagPagination.current ?? 1;
    const size = tagPagination.pageSize ?? 20;
    loadTags(current, size);
    refreshTagStats();
  }, [activeTab, loadTags, refreshTagStats, tagPagination]);

  useEffect(() => {
    if (activeTab !== "channels") return;
    const current = channelPagination.current ?? 1;
    const size = channelPagination.pageSize ?? 20;
    loadChannels(current, size);
  }, [activeTab, loadChannels, channelPagination]);

  useEffect(() => {
    if (activeTab !== "types") return;
    const current = typePagination.current ?? 1;
    const size = typePagination.pageSize ?? 20;
    loadTypes(current, size);
  }, [activeTab, loadTypes, typePagination]);

  useEffect(() => {
    if (activeTab !== "sources") return;
    const current = sourcePagination.current ?? 1;
    const size = sourcePagination.pageSize ?? 20;
    loadSources(current, size);
  }, [activeTab, loadSources, sourcePagination]);

  const openModal = useCallback(
    (tag?: VulnerabilityTag) => {
      setEditingTag(tag ?? null);
      form.setFieldsValue({
        name: tag?.name ?? "",
        category: tag?.category ?? "",
        color: tag?.color ?? "#1890FF",
        description: tag?.description ?? "",
        is_system: tag?.is_system ?? false,
      });
      setModalOpen(true);
    },
    [form],
  );

  const closeModal = () => {
    setModalOpen(false);
    setEditingTag(null);
    form.resetFields();
  };

  const openChannelModal = useCallback(
    (channel?: DiscoveryChannel) => {
      setEditingChannel(channel ?? null);
      channelForm.setFieldsValue({
        name: channel?.name ?? "",
        label: channel?.label ?? "",
        description: channel?.description ?? "",
        is_system: channel?.is_system ?? false,
      });
      setChannelModalOpen(true);
    },
    [channelForm],
  );

  const closeChannelModal = () => {
    setChannelModalOpen(false);
    setEditingChannel(null);
    channelForm.resetFields();
  };

  const openSourceModal = useCallback(
    (src?: VulnerabilitySource) => {
      setEditingSource(src ?? null);
      sourceForm.setFieldsValue({
        name: src?.name ?? "",
        label: src?.label ?? "",
        description: src?.description ?? "",
        is_system: src?.is_system ?? false,
      });
      setSourceModalOpen(true);
    },
    [sourceForm],
  );

  const closeSourceModal = () => {
    setSourceModalOpen(false);
    setEditingSource(null);
    sourceForm.resetFields();
  };

  const openTypeModal = useCallback(
    (vulnType?: VulnerabilityType) => {
      setEditingType(vulnType ?? null);
      typeForm.setFieldsValue({
        name: vulnType?.name ?? "",
        category: vulnType?.category ?? "",
        default_severity: vulnType?.default_severity ?? config?.severity_levels?.[2] ?? "medium",
        description: vulnType?.description ?? "",
        is_system: vulnType?.is_system ?? false,
      });
      setTypeModalOpen(true);
    },
    [config, typeForm],
  );

  const closeTypeModal = () => {
    setTypeModalOpen(false);
    setEditingType(null);
    typeForm.resetFields();
  };

  const submitTag = async () => {
    try {
      const values = await form.validateFields();
      if (editingTag) {
        await updateVulnerabilityTag(editingTag.id, values);
        message.success("Tag updated");
      } else {
        await createVulnerabilityTag(values);
        message.success("Tag created");
      }
      closeModal();
      const current = tagPagination.current ?? 1;
      const size = tagPagination.pageSize ?? 20;
      loadTags(current, size);
      refreshTagStats();
      loadConfig();
    } catch (error) {
      if (error instanceof Error) {
        message.error(error.message);
      }
    }
  };

  const submitType = async () => {
    try {
      const values = await typeForm.validateFields();
      const payload: VulnerabilityTypePayload = {
        name: values.name,
        category: values.category,
        default_severity: values.default_severity,
        description: values.description,
      };
      if (editingType) {
        await updateVulnerabilityType(editingType.id, payload);
        message.success("Type updated");
      } else {
        await createVulnerabilityType({ ...payload, is_system: values.is_system ?? false });
        message.success("Type created");
      }
      closeTypeModal();
      const current = typePagination.current ?? 1;
      const size = typePagination.pageSize ?? 20;
      loadTypes(current, size);
      loadConfig();
    } catch (error) {
      if (error instanceof Error) {
        message.error(error.message);
      }
    }
  };

  const submitChannel = async () => {
    try {
      const values = await channelForm.validateFields();
      if (editingChannel) {
        await updateDiscoveryChannel(editingChannel.id, values);
        message.success("Channel updated");
      } else {
        await createDiscoveryChannel(values);
        message.success("Channel created");
      }
      closeChannelModal();
      const current = channelPagination.current ?? 1;
      const size = channelPagination.pageSize ?? 20;
      loadChannels(current, size);
      loadConfig();
    } catch (error) {
      if (error instanceof Error) {
        message.error(error.message);
      }
    }
  };

  const submitSource = async () => {
    try {
      const values = await sourceForm.validateFields();
      if (editingSource) {
        await updateVulnerabilitySource(editingSource.id, values);
        message.success("Source updated");
      } else {
        await createVulnerabilitySource(values);
        message.success("Source created");
      }
      closeSourceModal();
      const current = sourcePagination.current ?? 1;
      const size = sourcePagination.pageSize ?? 20;
      loadSources(current, size);
      loadConfig();
    } catch (error) {
      if (error instanceof Error) {
        message.error(error.message);
      }
    }
  };

  const handleDelete = useCallback(
    (tag: VulnerabilityTag) => {
      Modal.confirm({
        title: `Delete ${tag.name}?`,
        content: "This action cannot be undone.",
        okType: "danger",
        onOk: async () => {
          try {
            await deleteVulnerabilityTag(tag.id);
            message.success("Tag deleted");
            const current = tagPagination.current ?? 1;
            const size = tagPagination.pageSize ?? 20;
            loadTags(current, size);
            refreshTagStats();
          } catch (error) {
            message.error("Failed to delete tag");
          }
        },
      });
    },
    [loadTags, refreshTagStats, tagPagination],
  );

  const handleTypeDelete = useCallback(
    (vulnType: VulnerabilityType) => {
      Modal.confirm({
        title: `Delete ${vulnType.name}?`,
        content: "This action cannot be undone.",
        okType: "danger",
        onOk: async () => {
          try {
            await deleteVulnerabilityType(vulnType.id);
            message.success("Type deleted");
            const current = typePagination.current ?? 1;
            const size = typePagination.pageSize ?? 20;
            loadTypes(current, size);
            loadConfig();
          } catch (error) {
            message.error("Failed to delete type");
          }
        },
      });
    },
    [loadConfig, loadTypes, typePagination],
  );

  const handleChannelDelete = useCallback(
    (channel: DiscoveryChannel) => {
      Modal.confirm({
        title: `Delete ${channel.label}?`,
        content: "This action cannot be undone.",
        okType: "danger",
        onOk: async () => {
          try {
            await deleteDiscoveryChannel(channel.id);
            message.success("Channel deleted");
            const current = channelPagination.current ?? 1;
            const size = channelPagination.pageSize ?? 20;
            loadChannels(current, size);
          } catch (error) {
            message.error("Failed to delete channel");
          }
        },
      });
    },
    [channelPagination, loadChannels],
  );

  const handleSourceDelete = useCallback(
    (src: VulnerabilitySource) => {
      Modal.confirm({
        title: `Delete ${src.label}?`,
        content: "This action cannot be undone.",
        okType: "danger",
        onOk: async () => {
          try {
            await deleteVulnerabilitySource(src.id);
            message.success("Source deleted");
            const current = sourcePagination.current ?? 1;
            const size = sourcePagination.pageSize ?? 20;
            loadSources(current, size);
            loadConfig();
          } catch (error) {
            message.error("Failed to delete source");
          }
        },
      });
    },
    [loadConfig, loadSources, sourcePagination],
  );

  const tagColumns: ColumnsType<VulnerabilityTag> = useMemo(
    () => [
      {
        title: "Name",
        dataIndex: "name",
        key: "name",
        render: (value: string, record) => (
          <Space direction="vertical" size={0}>
            <Text strong>{value}</Text>
            <Text type="secondary" style={{ fontSize: 12 }}>
              ID: {record.id}
            </Text>
          </Space>
        ),
      },
      {
        title: "Category",
        dataIndex: "category",
        key: "category",
        render: (value: string) => value || "—",
      },
      {
        title: "Color",
        dataIndex: "color",
        key: "color",
        render: (value: string) => <Tag color={value}>{value}</Tag>,
      },
      {
        title: "Description",
        dataIndex: "description",
        key: "description",
        ellipsis: true,
        render: (value: string) => value || "—",
      },
      {
        title: "Usage",
        dataIndex: "usage_count",
        key: "usage_count",
        width: 100,
      },
      {
        title: "Type",
        key: "is_system",
        dataIndex: "is_system",
        width: 120,
        render: (value: boolean) => <Badge color={value ? "purple" : "blue"} text={value ? "System" : "Custom"} />,
      },
      {
        title: "Actions",
        key: "actions",
        width: 160,
        render: (_: unknown, record) => (
          <Space>
            <Button size="small" onClick={() => openModal(record)} disabled={!canManage}>
              Edit
            </Button>
            <Button
              size="small"
              danger
              disabled={!canManage || record.is_system}
              onClick={() => handleDelete(record)}
            >
              Delete
            </Button>
          </Space>
        ),
      },
    ],
    [canManage, handleDelete, openModal],
  );

  const categoryOptions = useMemo(() => {
    const byCategory = tagStats?.by_category ?? {};
    const keys = Object.keys(byCategory);
    return keys.map((key) => ({ label: key || "(uncategorized)", value: key }));
  }, [tagStats]);

  const typeCategoryOptions = useMemo(() => {
    const categories = new Set<string>();
    typeData.forEach((item) => {
      if (item.category) {
        categories.add(item.category);
      }
    });
    return Array.from(categories).map((value) => ({ label: value, value }));
  }, [typeData]);

  const channelColumns: ColumnsType<DiscoveryChannel> = useMemo(
    () => [
      {
        title: "Internal name",
        dataIndex: "name",
        key: "name",
        render: (value: string, record) => (
          <Space direction="vertical" size={0}>
            <Text strong>{value}</Text>
            <Text type="secondary" style={{ fontSize: 12 }}>
              ID: {record.id}
            </Text>
          </Space>
        ),
      },
      {
        title: "Label",
        dataIndex: "label",
        key: "label",
      },
      {
        title: "Description",
        dataIndex: "description",
        key: "description",
        ellipsis: true,
        render: (value: string) => value || "—",
      },
      {
        title: "Type",
        dataIndex: "is_system",
        key: "is_system",
        width: 120,
        render: (value: boolean) => <Badge color={value ? "purple" : "blue"} text={value ? "System" : "Custom"} />,
      },
      {
        title: "Actions",
        key: "actions",
        width: 160,
        render: (_: unknown, record) => (
          <Space>
            <Button size="small" onClick={() => openChannelModal(record)} disabled={!canManage}>
              Edit
            </Button>
            <Button
              size="small"
              danger
              disabled={!canManage || record.is_system}
              onClick={() => handleChannelDelete(record)}
            >
              Delete
            </Button>
          </Space>
        ),
      },
    ],
    [canManage, handleChannelDelete, openChannelModal],
  );

  const severityOptions = useMemo(
    () =>
      (config?.severity_levels ?? ["critical", "high", "medium", "low"]).map((level) => ({
        label: level.toUpperCase(),
        value: level,
      })),
    [config?.severity_levels],
  );

  const typeColumns: ColumnsType<VulnerabilityType> = useMemo(() => {
    const severityTag = (value?: string) => {
      const lowered = (value || "").toLowerCase();
      const color =
        lowered === "critical" ? "red" : lowered === "high" ? "volcano" : lowered === "medium" ? "gold" : "blue";
      return <Tag color={color}>{lowered ? lowered.toUpperCase() : "—"}</Tag>;
    };

    return [
      {
        title: "Name",
        dataIndex: "name",
        key: "name",
        render: (value: string, record) => (
          <Space direction="vertical" size={0}>
            <Text strong>{value}</Text>
            <Text type="secondary" style={{ fontSize: 12 }}>
              ID: {record.id}
            </Text>
          </Space>
        ),
      },
      {
        title: "Category",
        dataIndex: "category",
        key: "category",
        render: (value: string) => value || "—",
      },
      {
        title: "Default severity",
        dataIndex: "default_severity",
        key: "default_severity",
        render: (value: string) => severityTag(value),
      },
      {
        title: "Description",
        dataIndex: "description",
        key: "description",
        ellipsis: true,
        render: (value: string) => value || "—",
      },
      {
        title: "Usage",
        dataIndex: "usage_count",
        key: "usage_count",
        width: 100,
      },
      {
        title: "Type",
        dataIndex: "is_system",
        key: "is_system",
        width: 120,
        render: (value: boolean) => <Badge color={value ? "purple" : "blue"} text={value ? "System" : "Custom"} />,
      },
      {
        title: "Actions",
        key: "actions",
        width: 180,
        render: (_: unknown, record) => (
          <Space>
            <Button size="small" onClick={() => openTypeModal(record)} disabled={!canManage}>
              Edit
            </Button>
            <Button
              size="small"
              danger
              disabled={!canManage || record.is_system}
              onClick={() => handleTypeDelete(record)}
            >
              Delete
            </Button>
          </Space>
        ),
      },
    ];
  }, [canManage, handleTypeDelete, openTypeModal]);

  const sourceColumns: ColumnsType<VulnerabilitySource> = useMemo(
    () => [
      {
        title: "Name",
        dataIndex: "name",
        key: "name",
        render: (value: string, record) => (
          <Space direction="vertical" size={0}>
            <Text strong>{record.label || value}</Text>
            <Text type="secondary" style={{ fontSize: 12 }}>
              ID: {record.id} · Key: {value}
            </Text>
          </Space>
        ),
      },
      {
        title: "Description",
        dataIndex: "description",
        key: "description",
        ellipsis: true,
        render: (value: string) => value || "—",
      },
      {
        title: "Type",
        dataIndex: "is_system",
        key: "is_system",
        width: 120,
        render: (value: boolean) => <Badge color={value ? "purple" : "blue"} text={value ? "System" : "Custom"} />,
      },
      {
        title: "Actions",
        key: "actions",
        width: 180,
        render: (_: unknown, record) => (
          <Space>
            <Button size="small" onClick={() => openSourceModal(record)} disabled={!canManage}>
              Edit
            </Button>
            <Button
              size="small"
              danger
              disabled={!canManage || record.is_system}
              onClick={() => handleSourceDelete(record)}
            >
              Delete
            </Button>
          </Space>
        ),
      },
    ],
    [canManage, handleSourceDelete, openSourceModal],
  );

  const sourceSection = (
    <Space direction="vertical" size={16} style={{ width: "100%" }}>
      <Row justify="space-between" align="middle">
        <Col>
          <Title level={4} style={{ marginBottom: 4 }}>
            Sources
          </Title>
          <Paragraph type="secondary" style={{ margin: 0 }}>
            Define standardized ingestion sources for vulnerability submissions.
          </Paragraph>
        </Col>
        <Col>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => openSourceModal()} disabled={!canManage}>
            New source
          </Button>
        </Col>
      </Row>

      <Card>
        <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
          <Col xs={24} md={12}>
            <Input.Search
              allowClear
              placeholder="Search sources"
              value={sourceSearch}
              onChange={(event) => setSourceSearch(event.target.value)}
              onSearch={(value) => {
                setSourceSearch(value);
                setSourcePagination((prev) => ({ ...prev, current: 1 }));
              }}
            />
          </Col>
          <Col xs={24} md={12}>
            <Select
              style={{ width: "100%" }}
              value={sourceSystemFilter}
              options={SYSTEM_FILTER_OPTIONS}
              onChange={(value) => {
                setSourceSystemFilter(value);
                setSourcePagination((prev) => ({ ...prev, current: 1 }));
              }}
            />
          </Col>
        </Row>

        <Table<VulnerabilitySource>
          rowKey={(record) => String(record.id)}
          loading={sourceLoading}
          columns={sourceColumns}
          dataSource={sourceData}
          pagination={{
            ...sourcePagination,
            total: sourceTotal,
            showSizeChanger: true,
            onChange: (page, pageSize) => setSourcePagination({ current: page, pageSize }),
          }}
        />
      </Card>
    </Space>
  );

  if (configLoading) {
    return (
      <div style={{ display: "flex", justifyContent: "center", padding: 48 }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!config) {
    return (
      <Card>
        <Paragraph>No configuration data available.</Paragraph>
      </Card>
    );
  }

  const referenceSection = (
    <>
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={12}>
          <Card title="Severity Levels">
            <Space wrap>
              {config.severity_levels.map((level) => (
                <Tag key={level} color={level === "critical" ? "red" : level === "high" ? "volcano" : level === "medium" ? "gold" : "blue"}>
                  {level.toUpperCase()}
                </Tag>
              ))}
            </Space>
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card title="Discovery Channels">
            <Space wrap>
              {config.discovery_channels.map((channel) => (
                <Tag key={channel}>{channel}</Tag>
              ))}
            </Space>
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24} lg={12}>
          <Card title="Discovery Phases">
            <Space wrap>
              {config.discovery_phases.map((phase) => (
                <Tag key={phase}>{phase}</Tag>
              ))}
            </Space>
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card title="Network Environments">
            <Space wrap>
              {config.network_envs.map((env) => (
                <Tag key={env}>{env}</Tag>
              ))}
            </Space>
          </Card>
        </Col>
      </Row>

      <Card title="Vulnerability Types">
        <List
          itemLayout="vertical"
          dataSource={config.types}
          renderItem={(item) => (
            <List.Item>
              <List.Item.Meta
                title={
                  <Space size={12}>
                    <Text strong>{item.name}</Text>
                    <Tag>{item.category}</Tag>
                    <Tag color="geekblue">Default: {item.default_severity.toUpperCase()}</Tag>
                  </Space>
                }
                description={item.description}
              />
            </List.Item>
          )}
        />
      </Card>
    </>
  );

  const typeSection = (
    <Space direction="vertical" size={16} style={{ width: "100%" }}>
      <Row justify="space-between" align="middle">
        <Col>
          <Title level={4} style={{ marginBottom: 4 }}>
            Vulnerability Types
          </Title>
          <Paragraph type="secondary" style={{ margin: 0 }}>
            Curate reference types, default severities, and descriptions for analysts to reuse.
          </Paragraph>
        </Col>
        <Col>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => openTypeModal()} disabled={!canManage}>
            New type
          </Button>
        </Col>
      </Row>

      <Card>
        <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
          <Col xs={24} md={8}>
            <Input.Search
              allowClear
              placeholder="Search types"
              value={typeSearch}
              onChange={(event) => setTypeSearch(event.target.value)}
              onSearch={(value) => {
                setTypeSearch(value);
                setTypePagination((prev) => ({ ...prev, current: 1 }));
              }}
            />
          </Col>
          <Col xs={24} md={8}>
            <Select
              allowClear
              placeholder="Filter by category"
              options={typeCategoryOptions}
              value={typeCategoryFilter}
              style={{ width: "100%" }}
              onChange={(value) => {
                setTypeCategoryFilter(value);
                setTypePagination((prev) => ({ ...prev, current: 1 }));
              }}
            />
          </Col>
          <Col xs={24} md={4}>
            <Select
              allowClear
              placeholder="Default severity"
              options={severityOptions}
              value={typeSeverityFilter}
              style={{ width: "100%" }}
              onChange={(value) => {
                setTypeSeverityFilter(value);
                setTypePagination((prev) => ({ ...prev, current: 1 }));
              }}
            />
          </Col>
          <Col xs={24} md={4}>
            <Select
              style={{ width: "100%" }}
              value={typeSystemFilter}
              options={SYSTEM_FILTER_OPTIONS}
              onChange={(value) => {
                setTypeSystemFilter(value);
                setTypePagination((prev) => ({ ...prev, current: 1 }));
              }}
            />
          </Col>
        </Row>

        <Table<VulnerabilityType>
          rowKey={(record) => String(record.id)}
          loading={typeLoading}
          columns={typeColumns}
          dataSource={typeData}
          pagination={{
            ...typePagination,
            total: typeTotal,
            showSizeChanger: true,
            onChange: (page, pageSize) => setTypePagination({ current: page, pageSize }),
          }}
        />
      </Card>
    </Space>
  );

  const tagTotalValue = tagStats?.total ?? 0;
  const tagCategoryMap = tagStats?.by_category ?? {};

  const tagSection = (
    <Space direction="vertical" size={16} style={{ width: "100%" }}>
      <Row justify="space-between" align="middle">
        <Col>
          <Title level={4} style={{ marginBottom: 4 }}>
            Vulnerability Tags
          </Title>
          <Paragraph type="secondary" style={{ margin: 0 }}>
            Maintain reusable labels for classifying vulnerabilities across the platform.
          </Paragraph>
        </Col>
        <Col>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => openModal()} disabled={!canManage}>
            New tag
          </Button>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24} md={8}>
          <Card style={{ height: "100%" }}>
            <Statistic title="Total tags" value={tagTotalValue} />
          </Card>
        </Col>
        <Col xs={24} md={16}>
          <Card title="By category" style={{ height: "100%" }}>
            {Object.keys(tagCategoryMap).length === 0 ? (
              <Paragraph type="secondary" style={{ margin: 0 }}>
                No category data yet.
              </Paragraph>
            ) : (
              <Space wrap>
                {Object.entries(tagCategoryMap).map(([category, count]) => (
                  <Tag key={category} color="geekblue">
                    {category || "(uncategorized)"}: {count}
                  </Tag>
                ))}
              </Space>
            )}
          </Card>
        </Col>
      </Row>

      <Card>
        <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
          <Col xs={24} md={8}>
            <Input.Search
              allowClear
              placeholder="Search tags"
              value={search}
              onChange={(event) => {
                setSearch(event.target.value);
              }}
              onSearch={(value) => {
                setSearch(value);
                setTagPagination((prev) => ({ ...prev, current: 1 }));
              }}
            />
          </Col>
          <Col xs={24} md={8}>
            <Select
              allowClear
              placeholder="Filter by category"
              options={categoryOptions}
              value={categoryFilter}
              style={{ width: "100%" }}
              onChange={(value) => {
                setCategoryFilter(value);
                setTagPagination((prev) => ({ ...prev, current: 1 }));
              }}
            />
          </Col>
          <Col xs={24} md={8}>
            <Select
              style={{ width: "100%" }}
              value={systemFilter}
              options={SYSTEM_FILTER_OPTIONS}
              onChange={(value) => {
                setSystemFilter(value);
                setTagPagination((prev) => ({ ...prev, current: 1 }));
              }}
            />
          </Col>
        </Row>

        <Table<VulnerabilityTag>
          rowKey={(record) => String(record.id)}
          loading={tagLoading}
          columns={tagColumns}
          dataSource={tagData}
          pagination={{
            ...tagPagination,
            total: tagTotal,
            showSizeChanger: true,
            onChange: (page, pageSize) => setTagPagination({ current: page, pageSize }),
          }}
        />
      </Card>
    </Space>
  );

  const channelSection = (
    <Space direction="vertical" size={16} style={{ width: "100%" }}>
      <Row justify="space-between" align="middle">
        <Col>
          <Title level={4} style={{ marginBottom: 4 }}>
            Discovery Channels
          </Title>
          <Paragraph type="secondary" style={{ margin: 0 }}>
            Manage inbound discovery sources shown in filters and analytics.
          </Paragraph>
        </Col>
        <Col>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => openChannelModal()} disabled={!canManage}>
            New channel
          </Button>
        </Col>
      </Row>

      <Card>
        <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
          <Col xs={24} md={12}>
            <Input.Search
              allowClear
              placeholder="Search channels"
              value={channelSearch}
              onChange={(event) => setChannelSearch(event.target.value)}
              onSearch={(value) => {
                setChannelSearch(value);
                setChannelPagination((prev) => ({ ...prev, current: 1 }));
              }}
            />
          </Col>
          <Col xs={24} md={12}>
            <Select
              style={{ width: "100%" }}
              value={channelSystemFilter}
              options={SYSTEM_FILTER_OPTIONS}
              onChange={(value) => {
                setChannelSystemFilter(value);
                setChannelPagination((prev) => ({ ...prev, current: 1 }));
              }}
            />
          </Col>
        </Row>

        <Table<DiscoveryChannel>
          rowKey={(record) => String(record.id)}
          loading={channelLoading}
          columns={channelColumns}
          dataSource={channelData}
          pagination={{
            ...channelPagination,
            total: channelTotal,
            showSizeChanger: true,
            onChange: (page, pageSize) => setChannelPagination({ current: page, pageSize }),
          }}
        />
      </Card>
    </Space>
  );

  const lockedFieldSet = new Set(SUBMISSION_LOCKED_FIELDS);
  const selectedSubmissionFieldSet = new Set(submissionFields);
  const submissionPreviewFields = [
    "title",
    "severity_level",
    "vulnerability_type",
    "application",
    "source",
    "discovery_phase",
    "network_env",
    "description",
    "verification_steps",
    "poc_text",
  ];
  const submissionFieldLabels = new Map(
    SUBMISSION_FIELD_GROUPS.flatMap((group) =>
      group.fields.map((field) => [field.key, field.label] as const),
    ),
  );
  const saveSubmissionRequirements = async () => {
    setSavingSubmissionRequirements(true);
    try {
      const updated = await updateVulnerabilitySubmissionRequirements(
        normalizeSubmissionFields(submissionFields),
      );
      setConfig(updated);
      message.success("Submission requirements updated");
    } catch (error) {
      console.error(error);
      message.error("Failed to update submission requirements");
    } finally {
      setSavingSubmissionRequirements(false);
    }
  };
  const submissionRequirementsSection = (
    <Row gutter={[16, 16]}>
      <Col xs={24} xl={14}>
        <Card
          title="Submission Required Fields"
          extra={<Tag color="blue">{submissionFields.length} required</Tag>}
        >
          <Paragraph type="secondary">
            Choose which fields are required when users submit a new vulnerability.
            System-required fields are always enforced. Submitted time and SLA
            deadline are generated automatically.
          </Paragraph>
          <Space wrap style={{ marginBottom: 16 }}>
            <Button
              onClick={() => setSubmissionFields(normalizeSubmissionFields(SUBMISSION_RECOMMENDED_FIELDS))}
              disabled={!canManage}
            >
              Apply recommended defaults
            </Button>
            <Button
              onClick={() => setSubmissionFields(normalizeSubmissionFields(SUBMISSION_LOCKED_FIELDS))}
              disabled={!canManage}
            >
              System required only
            </Button>
            <Button
              type="primary"
              onClick={() => void saveSubmissionRequirements()}
              loading={savingSubmissionRequirements}
              disabled={!canManage}
            >
              Save requirements
            </Button>
          </Space>

          <Space direction="vertical" size={16} style={{ width: "100%" }}>
            {SUBMISSION_FIELD_GROUPS.map((group) => (
              <Card
                key={group.title}
                size="small"
                title={group.title}
                styles={{ body: { padding: 16 } }}
              >
                <Paragraph type="secondary" style={{ marginTop: 0 }}>
                  {group.description}
                </Paragraph>
                <Row gutter={[12, 12]}>
                  {group.fields.map((field) => {
                    const locked = lockedFieldSet.has(field.key);
                    const checked = selectedSubmissionFieldSet.has(field.key);
                    return (
                      <Col xs={24} md={12} key={field.key}>
                        <Card
                          size="small"
                          styles={{
                            body: {
                              minHeight: 92,
                              background: checked ? "#f0f7ff" : undefined,
                            },
                          }}
                        >
                          <Space align="start">
                            <Checkbox
                              checked={checked}
                              disabled={locked || !canManage}
                              onChange={(event) => {
                                const next = new Set(submissionFields);
                                if (event.target.checked) {
                                  next.add(field.key);
                                } else {
                                  next.delete(field.key);
                                }
                                setSubmissionFields(normalizeSubmissionFields(Array.from(next)));
                              }}
                            />
                            <div>
                              <Space wrap size={6}>
                                <Text strong>{field.label}</Text>
                                {locked ? (
                                  <Tag color="orange">System required</Tag>
                                ) : checked ? (
                                  <Tag color="green">Required</Tag>
                                ) : (
                                  <Tag>Optional</Tag>
                                )}
                              </Space>
                              <Paragraph type="secondary" style={{ margin: "4px 0 0" }}>
                                {field.help}
                              </Paragraph>
                            </div>
                          </Space>
                        </Card>
                      </Col>
                    );
                  })}
                </Row>
              </Card>
            ))}
          </Space>
        </Card>
      </Col>
      <Col xs={24} xl={10}>
        <Space direction="vertical" size={16} style={{ width: "100%" }}>
          <Card title="Submission Form Preview">
            <Row gutter={[12, 12]}>
              {submissionPreviewFields.map((fieldKey) => (
                <Col
                  xs={24}
                  md={fieldKey === "description" || fieldKey === "verification_steps" || fieldKey === "poc_text" ? 24 : 12}
                  key={fieldKey}
                >
                  <Form.Item
                    label={submissionFieldLabels.get(fieldKey) ?? fieldKey}
                    required={selectedSubmissionFieldSet.has(fieldKey)}
                    style={{ marginBottom: 0 }}
                  >
                    {fieldKey === "description" || fieldKey === "verification_steps" || fieldKey === "poc_text" ? (
                      <Input.TextArea rows={3} disabled />
                    ) : (
                      <Input disabled />
                    )}
                  </Form.Item>
                </Col>
              ))}
            </Row>
          </Card>
          <Card title="API Preview">
            <pre style={{ margin: 0, whiteSpace: "pre-wrap" }}>
              {JSON.stringify({ submission_required_fields: submissionFields }, null, 2)}
            </pre>
          </Card>
        </Space>
      </Col>
    </Row>
  );

  return (
    <Space direction="vertical" size={24} style={{ width: "100%" }}>
      <div>
        <Title level={3} style={{ marginBottom: 4 }}>
          Vulnerability Configuration
        </Title>
        <Paragraph type="secondary" style={{ margin: 0 }}>
          Reference data powering the vulnerability backlog, including severity levels, vulnerability types, discovery channels, and tag definitions.
        </Paragraph>
      </div>

      <Tabs
        activeKey={activeTab}
        onChange={(key) => setActiveTab(key)}
        items={[
          { key: "reference", label: "Reference Data" },
          { key: "types", label: "Vulnerability Types" },
          { key: "tags", label: "Tag Management" },
          { key: "channels", label: "Discovery Channels" },
          { key: "sources", label: "Sources" },
          { key: "submission", label: "Submission Requirements" },
          { key: "sla", label: "SLA Rules" },
        ]}
      />

      {activeTab === "reference"
        ? referenceSection
        : activeTab === "types"
          ? typeSection
          : activeTab === "tags"
            ? tagSection
            : activeTab === "channels"
              ? channelSection
              : activeTab === "sources"
                ? sourceSection
                : activeTab === "submission"
                  ? submissionRequirementsSection
                  : (
              <Row gutter={[16, 16]}>
                <Col xs={24} lg={12}>
                  <Card title="SLA Rules (hours)" loading={configLoading}>
                    <Form
                      form={slaForm}
                      layout="vertical"
                      onFinish={async (values) => {
                        setSavingSLA(true);
                        try {
                          const updated = await updateVulnerabilitySLA({
                            critical: Number(values.critical),
                            high: Number(values.high),
                            medium: Number(values.medium),
                            low: Number(values.low),
                          });
                          setConfig(updated);
                          message.success("SLA rules updated");
                        } catch (err) {
                          console.error(err);
                          message.error("Failed to update SLA rules");
                        } finally {
                          setSavingSLA(false);
                        }
                      }}
                      initialValues={{
                        critical: config?.sla_rules?.critical ?? 24,
                        high: config?.sla_rules?.high ?? 72,
                        medium: config?.sla_rules?.medium ?? 168,
                        low: config?.sla_rules?.low ?? 336,
                      }}
                    >
                      <Form.Item label="Critical" name="critical" rules={[{ required: true }]}>
                        <Input type="number" min={1} addonAfter="hours" />
                      </Form.Item>
                      <Form.Item label="High" name="high" rules={[{ required: true }]}>
                        <Input type="number" min={1} addonAfter="hours" />
                      </Form.Item>
                      <Form.Item label="Medium" name="medium" rules={[{ required: true }]}>
                        <Input type="number" min={1} addonAfter="hours" />
                      </Form.Item>
                      <Form.Item label="Low" name="low" rules={[{ required: true }]}>
                        <Input type="number" min={1} addonAfter="hours" />
                      </Form.Item>
                      <Button type="primary" htmlType="submit" loading={savingSLA} disabled={!canManage}>
                        Save SLA
                      </Button>
                    </Form>
                  </Card>
                </Col>
                <Col xs={24} lg={12}>
                  <Card title="Guidance">
                    <List
                      dataSource={[
                        "Critical: respond within 24h",
                        "High: respond within 72h",
                        "Medium: respond within 7 days",
                        "Low: respond within 14 days",
                      ]}
                      renderItem={(item) => <List.Item>{item}</List.Item>}
                    />
                  </Card>
                </Col>
              </Row>
            )}

      <Modal
        title={editingType ? `Edit ${editingType.name}` : "Create vulnerability type"}
        open={typeModalOpen}
        onCancel={closeTypeModal}
        onOk={submitType}
        okText={editingType ? "Save" : "Create"}
        destroyOnClose
      >
        <Form layout="vertical" form={typeForm} preserve={false}>
          <Form.Item name="name" label="Name" rules={[{ required: true, message: "Name is required" }]}>
            <Input disabled={editingType?.is_system} placeholder="e.g., SQL Injection" />
          </Form.Item>
          <Form.Item name="category" label="Category">
            <Input placeholder="e.g., Web, Application, Third-Party" />
          </Form.Item>
          <Form.Item
            name="default_severity"
            label="Default severity"
            rules={[{ required: true, message: "Default severity is required" }]}
          >
            <Select options={severityOptions} />
          </Form.Item>
          <Form.Item name="description" label="Description">
            <Input.TextArea rows={3} placeholder="How to identify or apply this type" />
          </Form.Item>
          <Form.Item name="is_system" label="System type" valuePropName="checked">
            <Switch disabled={editingType?.is_system} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={editingTag ? `Edit ${editingTag.name}` : "Create tag"}
        open={modalOpen}
        onCancel={closeModal}
        onOk={submitTag}
        okText={editingTag ? "Save" : "Create"}
        destroyOnClose
      >
        <Form layout="vertical" form={form} preserve={false}>
          <Form.Item name="name" label="Name" rules={[{ required: true, message: "Name is required" }]}>
            <Input disabled={editingTag?.is_system} placeholder="e.g., SQLi" />
          </Form.Item>
          <Form.Item name="category" label="Category">
            <Input placeholder="e.g., web, dependency" />
          </Form.Item>
          <Form.Item name="color" label="Color">
            <Input type="color" />
          </Form.Item>
          <Form.Item name="description" label="Description">
            <Input.TextArea rows={3} placeholder="Optional description" />
          </Form.Item>
          <Form.Item name="is_system" label="System tag" valuePropName="checked">
            <Switch disabled={editingTag?.is_system} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={editingChannel ? `Edit ${editingChannel.label}` : "Create discovery channel"}
        open={channelModalOpen}
        onCancel={closeChannelModal}
        onOk={submitChannel}
        okText={editingChannel ? "Save" : "Create"}
        destroyOnClose
      >
        <Form layout="vertical" form={channelForm} preserve={false}>
          <Form.Item name="name" label="Internal name" rules={[{ required: true, message: "Name is required" }]}>
            <Input disabled={editingChannel?.is_system} placeholder="e.g., white_box" />
          </Form.Item>
          <Form.Item name="label" label="Display label" rules={[{ required: true, message: "Label is required" }]}>
            <Input placeholder="e.g., White-box review" />
          </Form.Item>
          <Form.Item name="description" label="Description">
            <Input.TextArea rows={3} placeholder="Optional description" />
          </Form.Item>
          <Form.Item name="is_system" label="System channel" valuePropName="checked">
            <Switch disabled={editingChannel?.is_system} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={editingSource ? `Edit ${editingSource.label}` : "Create source"}
        open={sourceModalOpen}
        onCancel={closeSourceModal}
        onOk={submitSource}
        okText={editingSource ? "Save" : "Create"}
        destroyOnClose
      >
        <Form layout="vertical" form={sourceForm} preserve={false}>
          <Form.Item name="name" label="Key" rules={[{ required: true, message: "Key is required" }]}>
            <Input disabled={editingSource?.is_system} placeholder="e.g., bug_bounty" />
          </Form.Item>
          <Form.Item name="label" label="Label" rules={[{ required: true, message: "Label is required" }]}>
            <Input placeholder="e.g., Bug bounty" />
          </Form.Item>
          <Form.Item name="description" label="Description">
            <Input.TextArea rows={3} placeholder="Optional description" />
          </Form.Item>
          <Form.Item name="is_system" label="System source" valuePropName="checked">
            <Switch disabled={editingSource?.is_system} />
          </Form.Item>
        </Form>
      </Modal>
    </Space>
  );
}
