import PromptPopup from '@renderer/components/Popups/PromptPopup'
import { useAssistant } from '@renderer/hooks/useAssistant'
import { useShowRightSidebar } from '@renderer/hooks/useStore'
import { fetchMessagesSummary } from '@renderer/services/api'
import { Assistant, Topic } from '@renderer/types'
import { Dropdown, MenuProps } from 'antd'
import { FC } from 'react'
import styled from 'styled-components'
import { DeleteOutlined, EditOutlined, SignatureOutlined } from '@ant-design/icons'
import LocalStorage from '@renderer/services/storage'
import { DragDropContext, Draggable, Droppable, DropResult } from '@hello-pangea/dnd'
import { droppableReorder } from '@renderer/utils'
import { useTranslation } from 'react-i18next'
import { useAppSelector } from '@renderer/store'

interface Props {
  assistant: Assistant
  activeTopic: Topic
  setActiveTopic: (topic: Topic) => void
}

const TopicsTab: FC<Props> = ({ assistant: _assistant, activeTopic, setActiveTopic }) => {
  const { rightSidebarShown } = useShowRightSidebar()
  const { assistant, removeTopic, updateTopic, updateTopics } = useAssistant(_assistant.id)
  const { t } = useTranslation()
  const generating = useAppSelector((state) => state.runtime.generating)

  const getTopicMenuItems = (topic: Topic) => {
    const menus: MenuProps['items'] = [
      {
        label: t('assistant.topics.auto_rename'),
        key: 'auto-rename',
        icon: <SignatureOutlined />,
        async onClick() {
          const messages = await LocalStorage.getTopicMessages(topic.id)
          if (messages.length >= 2) {
            const summaryText = await fetchMessagesSummary({ messages, assistant })
            if (summaryText) {
              updateTopic({ ...topic, name: summaryText })
            }
          }
        }
      },
      {
        label: t('common.rename'),
        key: 'rename',
        icon: <EditOutlined />,
        async onClick() {
          const name = await PromptPopup.show({
            title: t('assistant.topics.edit.title'),
            message: t('assistant.topics.edit.placeholder'),
            defaultValue: topic?.name || ''
          })
          if (name && topic?.name !== name) {
            updateTopic({ ...topic, name })
          }
        }
      }
    ]

    if (assistant.topics.length > 1) {
      menus.push({ type: 'divider' })
      menus.push({
        label: t('common.delete'),
        danger: true,
        key: 'delete',
        icon: <DeleteOutlined />,
        onClick() {
          if (assistant.topics.length === 1) return
          removeTopic(topic)
          setActiveTopic(assistant.topics[0])
        }
      })
    }

    return menus
  }

  const onDragEnd = (result: DropResult) => {
    if (result.destination) {
      const sourceIndex = result.source.index
      const destIndex = result.destination.index
      updateTopics(droppableReorder(assistant.topics, sourceIndex, destIndex))
    }
  }

  const onSwitchTopic = (topic: Topic) => {
    if (generating) {
      window.message.warning({ content: t('message.switch.disabled'), key: 'switch-assistant' })
      return
    }
    setActiveTopic(topic)
  }

  return (
    <Container style={{ display: rightSidebarShown ? 'block' : 'none' }}>
      <DragDropContext onDragEnd={onDragEnd}>
        <Droppable droppableId="droppable">
          {(provided) => (
            <div {...provided.droppableProps} ref={provided.innerRef}>
              {assistant.topics.map((topic, index) => (
                <Draggable key={`draggable_${topic.id}_${index}`} draggableId={topic.id} index={index}>
                  {(provided) => (
                    <div ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps}>
                      <Dropdown menu={{ items: getTopicMenuItems(topic) }} trigger={['contextMenu']} key={topic.id}>
                        <TopicListItem
                          className={topic.id === activeTopic?.id ? 'active' : ''}
                          onClick={() => onSwitchTopic(topic)}>
                          {topic.name}
                        </TopicListItem>
                      </Dropdown>
                    </div>
                  )}
                </Draggable>
              ))}
            </div>
          )}
        </Droppable>
      </DragDropContext>
    </Container>
  )
}

const Container = styled.div`
  padding: 15px 10px;
`

const TopicListItem = styled.div`
  padding: 8px 10px;
  margin-bottom: 5px;
  cursor: pointer;
  border-radius: 5px;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  &:hover {
    background-color: var(--color-background-soft);
  }
  &.active {
    background-color: var(--color-background-mute);
    font-weight: bolder;
  }
`

export default TopicsTab
