// SPDX-FileCopyrightText: 2025 Weibo, Inc.
//
// SPDX-License-Identifier: Apache-2.0

/**
 * KnowledgeGroupListPage - Displays knowledge bases in a table format.
 *
 * Shows a table of knowledge bases with search, sort, and create actions.
 * Supports two modes:
 * - Group mode: Shows KBs in a specific group
 * - All mode: Shows all KBs with group info column
 */

'use client'

import { useState, useMemo, useCallback } from 'react'
import { getKbShareSourceText } from '@/features/knowledge/utils/share-source'
import {
  ArrowLeft,
  Plus,
  BookOpen,
  Database,
  FolderOpen,
  Star,
  ChevronDown,
  ChevronUp,
  Pencil,
  Trash2,
  FolderOutput,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Spinner } from '@/components/ui/spinner'
import {
  Table,
  TableHeader,
  TableBody,
  TableRow,
  TableHead,
  TableCell,
} from '@/components/ui/table'
import { useTranslation } from '@/hooks/useTranslation'
import { cn } from '@/lib/utils'
import type {
  KnowledgeBase,
  KnowledgeBaseType,
  KnowledgeBaseWithGroupInfo,
  KbGroupInfo,
  MemberRole,
} from '@/types/knowledge'
import { ROLE_DISPLAY_NAMES } from '@/types/base-role'

/** Union type for KB data that can be either KnowledgeBase or KnowledgeBaseWithGroupInfo */
export type KbDataItem = KnowledgeBase | KnowledgeBaseWithGroupInfo

export interface KnowledgeGroupListPageProps {
  /** Group ID (null for "All" mode) */
  groupId: string | null
  /** Group display name */
  groupName: string
  /** Knowledge bases in this group */
  knowledgeBases: KnowledgeBase[]
  /** Knowledge bases with group info (for "All" mode) */
  knowledgeBasesWithGroupInfo?: KnowledgeBaseWithGroupInfo[]
  /** Whether data is loading */
  isLoading: boolean
  /** Go back handler (optional, hidden in "All" mode) */
  onBack?: () => void
  /** Select a knowledge base */
  onSelectKb: (kb: KbDataItem) => void
  /** Create a new knowledge base */
  onCreateKb?: (kbType: KnowledgeBaseType) => void
  /** Edit a knowledge base */
  onEditKb?: (kb: KbDataItem) => void
  /** Delete a knowledge base */
  onDeleteKb?: (kb: KbDataItem) => void
  /** Whether current user can manage a specific KB */
  canManageKb?: (kb: KbDataItem) => boolean
  /** Toggle favorite */
  onToggleFavorite?: (kbId: number, isFavorite: boolean) => void
  /** Check if KB is favorite */
  isFavorite?: (kbId: number) => boolean
  /** Get group info for a KB (for "All" mode) */
  getKbGroupInfo?: (kb: KbDataItem) => KbGroupInfo
  /** Whether this is "All" mode */
  isAllMode?: boolean
  /** Filter by group ID (for "All" mode) */
  filterGroupId?: string | null
  /** Set filter group ID (for "All" mode) */
  onFilterGroupChange?: (groupId: string | null) => void
  /** Available groups for filter (for "All" mode) */
  availableGroups?: Array<{ id: string; name: string; displayName: string }>
  /** Whether this is "Personal" mode (to show created/shared sections) */
  isPersonalMode?: boolean
  /** Knowledge bases created by current user (for personal mode) */
  personalCreatedByMe?: KnowledgeBaseWithGroupInfo[]
  /** Knowledge bases shared with current user (for personal mode) */
  personalSharedWithMe?: KnowledgeBaseWithGroupInfo[]
  /** Native group knowledge bases (for group section mode) */
  groupNativeKbs?: KnowledgeBaseWithGroupInfo[]
  /** Shared-into-group knowledge bases (for group section mode) */
  groupSharedKbs?: KnowledgeBaseWithGroupInfo[]
  /** Migrate a knowledge base to group */
  onMigrateKb?: (kb: KbDataItem) => void
  /** Check if user can migrate a KB (only for personal KBs created by user) */
  canMigrate?: (kb: KbDataItem) => boolean
}

type SortBy = 'name' | 'created' | 'updated' | 'group' | 'permission'
type SortOrder = 'asc' | 'desc'

/** Role priority for sorting (lower number = higher priority) */
const ROLE_PRIORITY: Record<string, number> = {
  Owner: 1,
  Maintainer: 2,
  Developer: 3,
  Reporter: 4,
  RestrictedAnalyst: 5,
}

/** Get role priority for sorting */
function getRolePriority(role: string | null | undefined): number {
  if (!role) return 999 // No role = lowest priority
  return ROLE_PRIORITY[role] ?? 999
}

/** Format date time: current year shows "x月xx日 xx:xx", previous years show "xxxx年x月xx日 xx:xx" */
function formatDateTime(dateStr: string | undefined, locale: string): string {
  if (!dateStr) return '--'

  const date = new Date(dateStr)
  const now = new Date()
  const isCurrentYear = date.getFullYear() === now.getFullYear()

  // Use locale-aware formatting
  if (isCurrentYear) {
    // Current year: "5月19日 14:30"
    return date.toLocaleDateString(locale, {
      month: 'numeric',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    })
  } else {
    // Previous years: "2025年5月19日 14:30"
    return date.toLocaleDateString(locale, {
      year: 'numeric',
      month: 'numeric',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    })
  }
}

/** Get icon for KB type */
/** Get icon for KB type */
function KbTypeIcon({ kbType, className }: { kbType?: string; className?: string }) {
  const isClassic = kbType === 'classic'
  if (isClassic) {
    return <Database className={cn('text-text-secondary', className)} />
  }
  return <BookOpen className={cn('text-primary', className)} />
}
export function KnowledgeGroupListPage({
  groupId: _groupId,
  groupName,
  knowledgeBases,
  knowledgeBasesWithGroupInfo,
  isLoading,
  onBack,
  onSelectKb,
  onCreateKb,
  onEditKb,
  onDeleteKb,
  canManageKb,
  onToggleFavorite,
  isFavorite,
  getKbGroupInfo,
  isAllMode = false,
  filterGroupId,
  onFilterGroupChange: _onFilterGroupChange,
  availableGroups: _availableGroups,
  isPersonalMode = false,
  personalCreatedByMe = [],
  personalSharedWithMe = [],
  groupNativeKbs = [],
  groupSharedKbs = [],
  onMigrateKb,
  canMigrate,
}: KnowledgeGroupListPageProps) {
  const isGroupSectionMode = groupNativeKbs.length > 0 || groupSharedKbs.length > 0
  const { t } = useTranslation('knowledge')
  const [sortBy, setSortBy] = useState<SortBy>('created')
  const [sortOrder, setSortOrder] = useState<SortOrder>('desc')

  // Determine which data source to use
  // Prefer knowledgeBasesWithGroupInfo when available (has my_role field)
  const dataSource = useMemo(() => {
    if (knowledgeBasesWithGroupInfo && knowledgeBasesWithGroupInfo.length > 0) {
      return knowledgeBasesWithGroupInfo
    }
    return knowledgeBases
  }, [knowledgeBasesWithGroupInfo, knowledgeBases])

  // Helper function to get my_role from KB
  const getKbRole = useCallback((kb: KbDataItem): string | null | undefined => {
    if ('my_role' in kb) {
      return kb.my_role
    }
    return undefined
  }, [])

  // Sort function for knowledge bases
  const sortKbs = useCallback(
    (kbs: KbDataItem[]) => {
      // Pre-compute timestamps for date-based sorting to avoid creating Date objects in each comparison
      const withTimestamps = kbs.map(kb => ({
        kb,
        createdTime: kb.created_at ? new Date(kb.created_at).getTime() : 0,
        updatedTime: kb.updated_at ? new Date(kb.updated_at).getTime() : 0,
      }))

      withTimestamps.sort((a, b) => {
        let comparison = 0
        switch (sortBy) {
          case 'name':
            comparison = a.kb.name.localeCompare(b.kb.name)
            break
          case 'created':
            comparison = a.createdTime - b.createdTime
            break
          case 'updated':
            comparison = a.updatedTime - b.updatedTime
            break
          case 'group':
            if (getKbGroupInfo) {
              const groupA = getKbGroupInfo(a.kb).groupName
              const groupB = getKbGroupInfo(b.kb).groupName
              comparison = groupA.localeCompare(groupB)
            }
            break
          case 'permission':
            comparison = getRolePriority(getKbRole(a.kb)) - getRolePriority(getKbRole(b.kb))
            break
          default:
            comparison = 0
        }
        return sortOrder === 'asc' ? comparison : -comparison
      })

      return withTimestamps.map(item => item.kb)
    },
    [sortBy, sortOrder, getKbGroupInfo, getKbRole]
  )

  // Filter and sort knowledge bases
  const filteredKbs = useMemo(() => {
    let result = [...dataSource]

    // Filter by group (for "All" mode)
    if (isAllMode && filterGroupId) {
      result = result.filter(kb => {
        if (getKbGroupInfo) {
          const groupInfo = getKbGroupInfo(kb)
          return groupInfo.groupId === filterGroupId
        }
        return true
      })
    }

    // Dedup by ID as a safety measure against duplicate data
    const seen = new Set<number>()
    result = result.filter(kb => {
      if (seen.has(kb.id)) return false
      seen.add(kb.id)
      return true
    })

    return sortKbs(result)
  }, [dataSource, isAllMode, filterGroupId, getKbGroupInfo, sortKbs])

  // Determine whether to show the "from" column
  const showFromColumn = !isPersonalMode && !isAllMode

  // Sorted personal KBs for personal mode
  const sortedCreatedByMe = useMemo(
    () => sortKbs(personalCreatedByMe),
    [personalCreatedByMe, sortKbs]
  )
  const sortedSharedWithMe = useMemo(
    () => sortKbs(personalSharedWithMe),
    [personalSharedWithMe, sortKbs]
  )
  const sortedNative = useMemo(() => sortKbs(groupNativeKbs), [groupNativeKbs, sortKbs])
  const sortedShared = useMemo(() => sortKbs(groupSharedKbs), [groupSharedKbs, sortKbs])

  const handleToggleFavorite = useCallback(
    (e: React.MouseEvent, kb: KbDataItem) => {
      e.stopPropagation()
      if (onToggleFavorite && isFavorite) {
        onToggleFavorite(kb.id, !isFavorite(kb.id))
      }
    },
    [onToggleFavorite, isFavorite]
  )

  const handleSort = useCallback(
    (column: SortBy) => {
      if (sortBy === column) {
        setSortOrder(prev => (prev === 'asc' ? 'desc' : 'asc'))
      } else {
        setSortBy(column)
        setSortOrder('desc')
      }
    },
    [sortBy]
  )

  const SortIcon = ({ column }: { column: SortBy }) => {
    if (sortBy !== column) return null
    return sortOrder === 'asc' ? (
      <ChevronUp className="w-3.5 h-3.5 ml-1" />
    ) : (
      <ChevronDown className="w-3.5 h-3.5 ml-1" />
    )
  }

  // Render table header
  const renderTableHeader = (
    showGroupColumn: boolean,
    showFromColumn: boolean,
    groupColumnTitle?: string
  ) => (
    <TableHeader className="sticky top-0 bg-surface">
      <TableRow className="text-left text-sm text-text-secondary">
        <TableHead className="h-auto px-6 py-3 font-medium w-[30%]">
          <button
            className="flex items-center hover:text-text-primary transition-colors"
            onClick={() => handleSort('name')}
          >
            {t('document.table.name', '名称')}
            <SortIcon column="name" />
          </button>
        </TableHead>
        {showGroupColumn && (
          <TableHead className="h-auto px-6 py-3 font-medium w-[15%]">
            <button
              className="flex items-center hover:text-text-primary transition-colors"
              onClick={() => handleSort('group')}
            >
              {groupColumnTitle || t('document.table.group', '归属')}
              <SortIcon column="group" />
            </button>
          </TableHead>
        )}
        {showFromColumn && (
          <TableHead className="h-auto px-6 py-3 font-medium w-[12%]">
            {t('document.table.from', '来自')}
          </TableHead>
        )}
        <TableHead className="h-auto px-6 py-3 font-medium w-[10%]">
          {t('document.table.permission', '权限')}
        </TableHead>
        <TableHead className="h-auto px-6 py-3 font-medium w-[12%]">
          <button
            className="flex items-center hover:text-text-primary transition-colors"
            onClick={() => handleSort('created')}
          >
            {t('document.table.createdAt', '创建时间')}
            <SortIcon column="created" />
          </button>
        </TableHead>
        <TableHead className="h-auto px-6 py-3 font-medium w-[12%]">
          <button
            className="flex items-center hover:text-text-primary transition-colors"
            onClick={() => handleSort('updated')}
          >
            {t('document.table.updatedAt', '更新时间')}
            <SortIcon column="updated" />
          </button>
        </TableHead>
        <TableHead className="h-auto px-6 py-3 font-medium w-[9%] text-right">
          {t('document.table.actions', '操作')}
        </TableHead>
      </TableRow>
    </TableHeader>
  )

  // Render table rows
  const renderTableRows = (
    kbs: KbDataItem[],
    showGroupColumn: boolean,
    showFromColumn: boolean
  ) => (
    <TableBody>
      {kbs.map(kb => (
        <KnowledgeBaseRow
          key={kb.id}
          kb={kb}
          onClick={() => onSelectKb(kb)}
          onEdit={onEditKb && canManageKb?.(kb) ? () => onEditKb(kb) : undefined}
          onDelete={onDeleteKb && canManageKb?.(kb) ? () => onDeleteKb(kb) : undefined}
          onMigrate={onMigrateKb ? () => onMigrateKb(kb) : undefined}
          onToggleFavorite={onToggleFavorite ? e => handleToggleFavorite(e, kb) : undefined}
          isFavorite={isFavorite?.(kb.id)}
          showGroupInfo={showGroupColumn}
          showFromInfo={showFromColumn}
          groupInfo={getKbGroupInfo?.(kb)}
          canMigrate={canMigrate?.(kb)}
        />
      ))}
    </TableBody>
  )

  // Render personal mode content with separate sections
  const renderPersonalModeContent = () => {
    const hasCreated = sortedCreatedByMe.length > 0
    const hasShared = sortedSharedWithMe.length > 0

    if (!hasCreated && !hasShared) {
      return (
        <div className="flex flex-col items-center justify-center py-12 text-center">
          <FolderOpen className="w-12 h-12 text-text-muted mb-4" />
          <h3 className="text-lg font-medium text-text-primary mb-2">
            {t('document.knowledgeBase.empty', '暂无知识库')}
          </h3>
          <p className="text-sm text-text-muted mb-4">
            {t('document.knowledgeBase.createDesc', '点击上方按钮创建第一个知识库')}
          </p>
        </div>
      )
    }

    return (
      <div className="space-y-6">
        {/* Created by me section */}
        <div>
          <h3 className="px-6 py-3 text-sm font-medium text-text-secondary bg-surface-hover border-b border-border">
            {t('document.personalGroups.createdByMe', '我创建的')}
            <span className="ml-2 text-text-muted">({sortedCreatedByMe.length})</span>
          </h3>
          {hasCreated ? (
            <Table className="w-full table-fixed min-w-0">
              {renderTableHeader(false, false)}
              {renderTableRows(sortedCreatedByMe, false, false)}
            </Table>
          ) : (
            <div className="px-6 py-8 text-center text-text-muted">
              <p>{t('document.personalGroups.noCreated', '您还没有创建任何知识库')}</p>
              <p className="text-sm mt-1">
                {t('document.personalGroups.createdDesc', '点击上方按钮创建您的第一个知识库')}
              </p>
            </div>
          )}
        </div>

        {/* Shared with me section */}
        <div>
          <h3 className="px-6 py-3 text-sm font-medium text-text-secondary bg-surface-hover border-b border-border">
            {t('document.personalGroups.sharedWithMe', '分享给我的')}
            <span className="ml-2 text-text-muted">({sortedSharedWithMe.length})</span>
          </h3>
          {hasShared ? (
            <Table className="w-full table-fixed min-w-0">
              {renderTableHeader(true, true, t('document.table.belongsTo', '归属'))}
              {renderTableRows(sortedSharedWithMe, true, true)}
            </Table>
          ) : (
            <div className="px-6 py-8 text-center text-text-muted">
              <p>{t('document.personalGroups.noShared', '暂没有分享给您的知识库')}</p>
              <p className="text-sm mt-1">
                {t(
                  'document.personalGroups.sharedDesc',
                  '当其他用户分享知识库给您时，将显示在这里'
                )}
              </p>
            </div>
          )}
        </div>
      </div>
    )
  }

  // Render group section mode with native and shared sub-sections
  const renderGroupSectionContent = () => {
    const hasNative = sortedNative.length > 0
    const hasShared = sortedShared.length > 0

    if (!hasNative && !hasShared) {
      return (
        <div className="flex flex-col items-center justify-center py-12 text-center">
          <FolderOpen className="w-12 h-12 text-text-muted mb-4" />
          <h3 className="text-lg font-medium text-text-primary mb-2">
            {t('document.knowledgeBase.empty', '暂无知识库')}
          </h3>
          <p className="text-sm text-text-muted mb-4">
            {t('document.knowledgeBase.createDesc', '点击上方按钮创建第一个知识库')}
          </p>
        </div>
      )
    }

    return (
      <div className="space-y-6">
        {/* Native group KBs section */}
        <div>
          <h3 className="px-6 py-3 text-sm font-medium text-text-secondary bg-surface-hover border-b border-border">
            {t('document.groupSections.native', '创建')}
            <span className="ml-2 text-text-muted">({sortedNative.length})</span>
          </h3>
          {hasNative ? (
            <Table className="w-full table-fixed min-w-0">
              {renderTableHeader(false, false)}
              {renderTableRows(sortedNative, false, false)}
            </Table>
          ) : (
            <div className="px-6 py-8 text-center text-text-muted">
              <p>{t('document.groupSections.noNative', '暂无群组知识库')}</p>
            </div>
          )}
        </div>

        {/* Shared-into-group KBs section */}
        <div>
          <h3 className="px-6 py-3 text-sm font-medium text-text-secondary bg-surface-hover border-b border-border">
            {t('document.groupSections.shared', '分享')}
            <span className="ml-2 text-text-muted">({sortedShared.length})</span>
          </h3>
          {hasShared ? (
            <Table className="w-full table-fixed min-w-0">
              {renderTableHeader(false, true)}
              {renderTableRows(sortedShared, false, true)}
            </Table>
          ) : (
            <div className="px-6 py-8 text-center text-text-muted">
              <p>{t('document.groupSections.noShared', '暂无分享的知识库')}</p>
            </div>
          )}
        </div>
      </div>
    )
  }

  return (
    <div
      className="flex flex-col h-full overflow-hidden pl-4"
      data-testid="knowledge-group-list-page"
    >
      {/* Header */}
      <div className="flex items-center gap-3 px-6 py-4 border-b border-border ml-2">
        {/* Back button - only show in group mode */}
        {!isAllMode && onBack && (
          <Button
            variant="ghost"
            size="icon"
            onClick={onBack}
            className="flex-shrink-0"
            data-testid="back-button"
          >
            <ArrowLeft className="w-4 h-4" />
          </Button>
        )}
        <h2 className="text-lg font-semibold flex-1 truncate">
          {isAllMode ? t('document.allKnowledgeBases', '全部知识库') : groupName}
        </h2>
        {onCreateKb && (
          <Button
            variant="primary"
            size="sm"
            onClick={() => onCreateKb('notebook')}
            data-testid="create-kb-button"
          >
            <Plus className="w-4 h-4 mr-1" />
            {t('document.knowledgeBase.create', '新建知识库')}
          </Button>
        )}
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto overflow-x-hidden min-w-0">
        {isLoading ? (
          <div className="flex items-center justify-center py-12">
            <Spinner />
          </div>
        ) : isPersonalMode ? (
          // Personal mode: show separate sections for created and shared
          renderPersonalModeContent()
        ) : isGroupSectionMode ? (
          // Group section mode: show native and shared sub-sections
          renderGroupSectionContent()
        ) : filteredKbs.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-12 text-center">
            <FolderOpen className="w-12 h-12 text-text-muted mb-4" />
            <h3 className="text-lg font-medium text-text-primary mb-2">
              {t('document.knowledgeBase.empty', '暂无知识库')}
            </h3>
            <p className="text-sm text-text-muted mb-4">
              {t('document.knowledgeBase.createDesc', '点击上方按钮创建第一个知识库')}
            </p>
          </div>
        ) : (
          <Table className="w-full table-fixed min-w-0">
            {renderTableHeader(isAllMode, showFromColumn)}
            {renderTableRows(filteredKbs, isAllMode, showFromColumn)}
          </Table>
        )}
      </div>
    </div>
  )
}

// Knowledge base table row component
interface KnowledgeBaseRowProps {
  kb: KbDataItem
  onClick: () => void
  onEdit?: () => void
  onDelete?: () => void
  onMigrate?: () => void
  onToggleFavorite?: (e: React.MouseEvent) => void
  isFavorite?: boolean
  showGroupInfo?: boolean
  showFromInfo?: boolean
  groupInfo?: KbGroupInfo
  canMigrate?: boolean
}

function KnowledgeBaseRow({
  kb,
  onClick,
  onEdit,
  onDelete,
  onMigrate,
  onToggleFavorite: _onToggleFavorite,
  isFavorite,
  showGroupInfo,
  showFromInfo,
  groupInfo,
  canMigrate,
}: KnowledgeBaseRowProps) {
  const { t, i18n } = useTranslation('knowledge')
  return (
    <TableRow
      className="border-b border-border hover:bg-surface-hover cursor-pointer transition-colors"
      onClick={onClick}
      data-testid={`kb-row-${kb.id}`}
    >
      {/* Name column */}
      <TableCell className="px-6 py-3 overflow-hidden">
        <div className="flex items-center gap-3 min-w-0">
          <KbTypeIcon kbType={kb.kb_type} className="w-5 h-5 flex-shrink-0" />
          <span className="text-sm font-medium text-text-primary truncate">{kb.name}</span>
          {isFavorite && <Star className="w-4 h-4 text-yellow-500 fill-yellow-500 flex-shrink-0" />}
        </div>
      </TableCell>

      {/* Group column - only in "All" mode */}
      {showGroupInfo && (
        <TableCell className="px-6 py-3 text-text-secondary overflow-hidden">
          <span className="truncate block">{groupInfo ? groupInfo.groupName : '--'}</span>
        </TableCell>
      )}

      {/* From column - shows who shared the KB */}
      {showFromInfo && (
        <TableCell className="px-6 py-3 text-text-secondary overflow-hidden">
          <span className="truncate block">
            {'group_type' in kb ? getKbShareSourceText(kb as KnowledgeBaseWithGroupInfo) : '--'}
          </span>
        </TableCell>
      )}

      {/* Permission column */}
      <TableCell className="px-6 py-3 text-text-secondary whitespace-nowrap">
        {'my_role' in kb && kb.my_role ? ROLE_DISPLAY_NAMES[kb.my_role as MemberRole] : '--'}
      </TableCell>

      {/* Created at column */}
      <TableCell className="px-6 py-3 text-text-secondary whitespace-nowrap">
        {formatDateTime(kb.created_at, i18n.language)}
      </TableCell>

      {/* Updated at column */}
      <TableCell className="px-6 py-3 text-text-secondary whitespace-nowrap">
        {formatDateTime(kb.updated_at, i18n.language)}
      </TableCell>

      {/* Actions column - Migrate, Edit and Delete */}
      <TableCell className="px-6 py-3">
        <div className="flex items-center justify-end gap-1">
          {canMigrate && onMigrate && (
            <Button
              variant="ghost"
              size="icon"
              className="h-8 w-8"
              onClick={e => {
                e.stopPropagation()
                onMigrate()
              }}
              title={t('document.migrate.title', '迁移到群组')}
              data-testid={`migrate-kb-${kb.id}`}
            >
              <FolderOutput className="w-4 h-4 text-text-muted hover:text-primary transition-colors" />
            </Button>
          )}
          {onEdit && (
            <Button
              variant="ghost"
              size="icon"
              className="h-8 w-8"
              onClick={e => {
                e.stopPropagation()
                onEdit()
              }}
              title={t('document.table.edit', '编辑')}
              data-testid={`edit-kb-${kb.id}`}
            >
              <Pencil className="w-4 h-4 text-text-muted" />
            </Button>
          )}
          {onDelete && (
            <Button
              variant="ghost"
              size="icon"
              className="h-8 w-8"
              onClick={e => {
                e.stopPropagation()
                onDelete()
              }}
              title={t('document.table.delete', '删除')}
              data-testid={`delete-kb-${kb.id}`}
            >
              <Trash2 className="w-4 h-4 text-text-muted hover:text-error" />
            </Button>
          )}
        </div>
      </TableCell>
    </TableRow>
  )
}

export default KnowledgeGroupListPage
