import { Button, Modal, ModalBody, ModalContent, ModalFooter, ModalHeader, Table, TableBody, TableCell, TableColumn, TableHeader, TableRow, getKeyValue } from '@nextui-org/react'
import React from 'react'
import { useAppDispatch, useAppSelector } from '@/store/hook'
import { deleteConversations } from '@/store/conversationSlice'
import useToast from '@/hooks/useToast'

interface ConversationModalProps {
  isOpen: boolean
  onClose: () => void
}

export const ConversationModal: React.FC<ConversationModalProps> = ({ isOpen, onClose }) => {
  const dispatch = useAppDispatch()
  const showToast = useToast()

  const tableColumns = [
    {
      key: 'conversationTitle',
      label: '对话名称',
    },
    {
      key: 'startTime',
      label: '对话发起时间',
    },
  ]

  const { currentConversationId, conversations } = useAppSelector(state => state.conversation)
  const [selectedKeys, setSelectedKeys] = React.useState(new Set([]))
  const allItems = conversations.filter(item => item.conversationId)
  const handleClose = () => {
    setSelectedKeys(new Set([]))
    onClose()
  }
  const handleDelete = async () => {
    const selectedKeysArray = Array.from(selectedKeys) as string[]
    if (selectedKeysArray.length > 0) {
      const resultAction = await dispatch(deleteConversations(selectedKeysArray))
      if (deleteConversations.fulfilled.match(resultAction)) {
        showToast('删除成功', 'success')
      }
      else {
        showToast('删除失败', 'error')
      }
    }
  }
  return (
    <Modal backdrop="blur" size="3xl" isOpen={isOpen} onClose={handleClose}>
      <ModalContent>
        {onClose => (
          <>
            <ModalHeader className="flex flex-col gap-1">
              <div>
                管理对话记录
                <span className="text-[#8D9795] text-[14px]">
                  （共
                  {allItems.length}
                  条）
                </span>
              </div>
            </ModalHeader>
            <ModalBody className="text-[#27353C]">
              <Table
                removeWrapper
                selectionMode="multiple"
                selectedKeys={selectedKeys}
                disabledKeys={[currentConversationId || '']}
                onSelectionChange={keys => setSelectedKeys(keys as any)}
                aria-label="table"
              >
                <TableHeader columns={tableColumns}>
                  {column => <TableColumn key={column.key}>{column.label}</TableColumn>}
                </TableHeader>
                <TableBody items={allItems}>
                  {item => (
                    <TableRow key={item.conversationId}>
                      {columnKey => <TableCell>{getKeyValue(item, columnKey)}</TableCell>}
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </ModalBody>
            <ModalFooter>
              <Button onPress={onClose}>
                取消
              </Button>
              <Button isDisabled={[...selectedKeys].length === 0} color="primary" onClick={handleDelete}>
                删除所选
              </Button>
            </ModalFooter>
          </>
        )}
      </ModalContent>
    </Modal>
  )
}
