'use client';

import { type Chat, deleteChat, listChats } from '@/api/chats';
import { actions } from '@/components/cells/actions';
import { datetime } from '@/components/cells/datetime';
import { link } from '@/components/cells/link';
import { metadataCell } from '@/components/cells/metadata';
import { DataTableRemote } from '@/components/data-table-remote';
import { createColumnHelper } from '@tanstack/table-core';
import { Trash2Icon } from 'lucide-react';

export function ChatsTable () {
  return (
    <DataTableRemote
      idColumn="id"
      apiKey="api.chats.list"
      api={listChats}
      columns={columns as any}
    />
  );
}

const helper = createColumnHelper<Chat>();

const columns = [
  helper.accessor('title', {
    header: "对话标题",
    cell: link({ url: chat => `/c/${chat.id}` }),
  }),
  helper.accessor('origin', { header: "来源" }),
  helper.accessor('created_at', { header: "创建于", cell: datetime }),
  helper.accessor('engine_id', { header: "智能体" }),
//  helper.accessor('engine_options', { header: "智能体配置", cell: metadataCell }),
  helper.display({
    header: '操作',
    cell: actions(chat => [
      {
        key: 'delete',
        title: '删除',
        icon: <Trash2Icon className="size-3" />,
        dangerous: {
          dialogTitle: '您确定删除该对话吗?',
          dialogDescription: '删除之后不能恢复',
        },
        action: async ({ table }) => {
          await deleteChat(chat.id);
          table.reload?.();
        },
      },
    ]),
  }),
];
