import { useState, KeyboardEvent, useEffect, useRef } from 'react'
import { Button, Card, FloatButton, Input, Select } from 'antd'
import { CircleArrowLeft, CircleArrowRight } from 'lucide-react'
import { OpenAIOutlined, ArrowUpOutlined } from '@ant-design/icons'
import { useAIStore, AIMessage } from '@/stores/ai'
import MarkdownRender from '../MarkdownRender'
import './AIChat.scss'

export const MessageItem = ({ message }: { message: AIMessage }) => {
  return (
    <div className={`message-item ${message.role}`}>
      <div className="message-box">
        <div className="message-content">
          <MarkdownRender>{message.content}</MarkdownRender>
        </div>
      </div>
    </div>
  )
}

export default function AIChat() {
  const { ai, setAI, options, post, messages, isLoading, collapsed, toggleCollapsed } = useAIStore()

  const [content, setContent] = useState('')

  const handleEnterSearch = (e: KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleAI()
    }
  }
  const handleAI = () => {
    setContent('')
    post({ messages: [{ role: 'user', content }] })
  }

  const messageScrollRef = useRef<HTMLDivElement | null>(null)
  useEffect(() => {
    if (messageScrollRef.current) {
      const scrollContainer = messageScrollRef.current
      scrollContainer.scrollTop = scrollContainer.scrollHeight
    }
  }, [messages])

  if (collapsed) {
    return (
      <Card
        className="app-card ai-chat"
        title="AI对话"
        extra={<span onClick={toggleCollapsed}>{collapsed ? <CircleArrowRight /> : <CircleArrowLeft />}</span>}>
        <div className="ai-chat-container">
          <div className="message-scroll" ref={messageScrollRef}>
            {messages.map((message, index) => {
              return <MessageItem message={message} key={index}></MessageItem>
            })}
          </div>
          <div className="input-container">
            <div className="input-box">
              <div className="edit-area">
                <Input.TextArea
                  className="content"
                  autoSize
                  value={content}
                  placeholder="shift+enter换行"
                  onChange={(e) => setContent(e.target.value)}
                  onKeyDown={handleEnterSearch}
                />
              </div>
            </div>
            <div className="input-tools">
              <Select
                value={ai}
                options={options}
                onChange={setAI}
                variant="filled"
                suffixIcon={null}
                popupMatchSelectWidth={110}></Select>
              <Button type="primary" shape="circle" icon={<ArrowUpOutlined />} onClick={handleAI} loading={isLoading} />
            </div>
            <div className="upload-list"></div>
          </div>
        </div>
      </Card>
    )
  } else {
    return <FloatButton icon={<OpenAIOutlined />} onClick={toggleCollapsed} />
  }
}
