import { useState, KeyboardEvent } 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 } from './useAIStore'
import AIBubbleList from './AIBubbleList'

import './AIChat.scss'

export default function AIChat() {
  const ai = useAIStore((state) => state.ai)
  const setAI = useAIStore((state) => state.setAI)
  const options = useAIStore((state) => state.options)
  const post = useAIStore((state) => state.post)
  const messages = useAIStore((state) => state.messages)
  const isLoading = useAIStore((state) => state.isLoading)
  const collapsed = useAIStore((state) => state.collapsed)
  const toggleCollapsed = useAIStore((state) => state.toggleCollapsed)

  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 }] })
  }

  if (collapsed) {
    return (
      <Card
        className="app-card ai-chat"
        title="AI对话"
        extra={<span onClick={toggleCollapsed}>{collapsed ? <CircleArrowRight /> : <CircleArrowLeft />}</span>}>
        <div className="ai-chat-container">
          <AIBubbleList messages={messages} style={{ height: '100%' }} />
          <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={140}></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} />
  }
}
