import { useCallback, useEffect, useMemo, useState } from 'react' import { flexRender, getCoreRowModel, getFilteredRowModel, getPaginationRowModel, useReactTable, type ColumnDef, type RowSelectionState, } from '@tanstack/react-table' import { Search } from 'lucide-react' import { useTranslation } from 'react-i18next' import { Button } from '@/components/ui/button' import { Checkbox } from '@/components/ui/checkbox' import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from '@/components/ui/dialog' import { Input } from '@/components/ui/input' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/components/ui/select' import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from '@/components/ui/table' import { DataTablePagination } from '@/components/data-table/pagination' import { StatusBadge } from '@/components/status-badge' import type { UpstreamChannel } from '../types' import { CHANNEL_STATUS_CONFIG, DEFAULT_ENDPOINT, ENDPOINT_OPTIONS, MODELS_DEV_PRESET_ID, OFFICIAL_CHANNEL_ID, } from './constants' type ChannelSelectorDialogProps = { open: boolean onOpenChange: (open: boolean) => void channels: UpstreamChannel[] selectedChannelIds: number[] onSelectedChannelIdsChange: (ids: number[]) => void channelEndpoints: Record onChannelEndpointsChange: (endpoints: Record) => void onConfirm: (selectedIds: number[]) => void } // Synthesized presets from `controller/ratio_sync.go` always carry stable // negative IDs, so matching by ID alone is reliable and self-documenting. function isOfficialChannel(channel: UpstreamChannel): boolean { return ( channel.id === OFFICIAL_CHANNEL_ID || channel.id === MODELS_DEV_PRESET_ID ) } export function ChannelSelectorDialog({ open, onOpenChange, channels, selectedChannelIds, onSelectedChannelIdsChange, channelEndpoints, onChannelEndpointsChange, onConfirm, }: ChannelSelectorDialogProps) { const { t } = useTranslation() const [search, setSearch] = useState('') const [rowSelection, setRowSelection] = useState({}) useEffect(() => { if (!selectedChannelIds.length) { setRowSelection({}) return } const availableChannelIds = new Set(channels.map((channel) => channel.id)) const newSelection: RowSelectionState = {} selectedChannelIds.forEach((id) => { if (availableChannelIds.has(id)) { newSelection[id.toString()] = true } }) setRowSelection(newSelection) }, [selectedChannelIds, channels]) const updateEndpoint = useCallback( (channelId: number, endpoint: string) => { onChannelEndpointsChange({ ...channelEndpoints, [channelId]: endpoint, }) }, [channelEndpoints, onChannelEndpointsChange] ) const getEndpointType = (endpoint: string) => { const option = ENDPOINT_OPTIONS.find((opt) => opt.value === endpoint) return option ? endpoint : 'custom' } const columns = useMemo[]>( () => [ { id: 'select', header: ({ table }) => ( table.toggleAllPageRowsSelected(!!value) } aria-label='Select all' /> ), cell: ({ row }) => ( row.toggleSelected(!!value)} aria-label='Select row' /> ), enableSorting: false, enableHiding: false, }, { accessorKey: 'name', header: t('Name'), cell: ({ row }) => { const name = row.getValue('name') as string const channel = row.original const isOfficial = isOfficialChannel(channel) return (
{name} {isOfficial && ( )}
) }, }, { accessorKey: 'base_url', header: t('Base URL'), cell: ({ row }) => { const url = row.getValue('base_url') as string return ( {url} ) }, }, { accessorKey: 'status', header: t('Status'), cell: ({ row }) => { const status = row.getValue('status') as number const config = CHANNEL_STATUS_CONFIG[status as keyof typeof CHANNEL_STATUS_CONFIG] if (!config) { return ( ) } return ( ) }, }, { id: 'endpoint', header: t('Sync Endpoint'), cell: ({ row }) => { const channel = row.original const currentEndpoint = channelEndpoints[channel.id] || DEFAULT_ENDPOINT const endpointType = getEndpointType(currentEndpoint) const handleTypeChange = (value: string) => { if (value === 'custom') { updateEndpoint(channel.id, '') } else { updateEndpoint(channel.id, value) } } return (
{endpointType === 'custom' && ( updateEndpoint(channel.id, e.target.value)} placeholder={t('/your/endpoint')} className='h-8 w-40 font-mono text-xs' /> )}
) }, }, ], [channelEndpoints, t, updateEndpoint] ) const filteredChannels = useMemo(() => { if (!search.trim()) return channels const searchLower = search.toLowerCase() return channels.filter( (ch) => ch.name.toLowerCase().includes(searchLower) || ch.base_url.toLowerCase().includes(searchLower) ) }, [channels, search]) const sortedChannels = useMemo(() => { return [...filteredChannels].sort((a, b) => { const aIsOfficial = isOfficialChannel(a) const bIsOfficial = isOfficialChannel(b) if (aIsOfficial && !bIsOfficial) return -1 if (!aIsOfficial && bIsOfficial) return 1 return 0 }) }, [filteredChannels]) const table = useReactTable({ data: sortedChannels, columns, state: { rowSelection, }, getRowId: (row) => row.id.toString(), enableRowSelection: true, onRowSelectionChange: setRowSelection, getCoreRowModel: getCoreRowModel(), getFilteredRowModel: getFilteredRowModel(), getPaginationRowModel: getPaginationRowModel(), initialState: { pagination: { pageSize: 10, }, }, }) const handleConfirm = () => { const selectedRows = table.getSelectedRowModel().rows const selectedIds = selectedRows.map((row) => row.original.id) onSelectedChannelIdsChange(selectedIds) onOpenChange(false) onConfirm(selectedIds) } return ( {t('Select Sync Channels')} {t('Choose channels to sync upstream ratio configurations from')}
setSearch(e.target.value)} className='ps-8' />
{table.getHeaderGroups().map((headerGroup) => ( {headerGroup.headers.map((header) => ( {header.isPlaceholder ? null : flexRender( header.column.columnDef.header, header.getContext() )} ))} ))} {table.getRowModel().rows?.length ? ( table.getRowModel().rows.map((row) => ( {row.getVisibleCells().map((cell) => ( {flexRender( cell.column.columnDef.cell, cell.getContext() )} ))} )) ) : ( {t('No channels found')} )}
) }