import React, { useEffect, useRef, useState } from 'react'
import { AnimatePresence, motion } from 'framer-motion'
import { Button } from '@nextui-org/react'
import { useToggle } from 'ahooks'
import { LoginModal } from '../LoginModal'
import type { RootState } from '@/store'
import SendIcon from '@/assets/svg/send.svg?react'
import { type WithAuthProps, withAuth } from '@/auth/withAuth'
import { useAppSelector } from '@/store/hook'

interface ChatEditorProps {
  onChange?: (value: string) => void
  onFocus?: () => void
  onSubmit?: (value: string) => void
  placeholders: string[]
}

const ChatEditorBase: React.FC<ChatEditorProps & WithAuthProps> = ({ checkAuth, onChange, onFocus, onSubmit, placeholders }) => {
  // const dispatch = useAppDispatch()
  const [content, setContent] = useState('')
  const editorRef = useRef<HTMLDivElement>(null)
  const [currentPlaceholder, setCurrentPlaceholder] = useState(0)
  const intervalRef = useRef<NodeJS.Timeout | null>(null)
  const [isOpenLoginModal, isOpenLoginModalActions] = useToggle()
  const isAsking = useAppSelector((state: RootState) => state.chat.isAsking)

  const startAnimation = () => {
    intervalRef.current = setInterval(() => {
      setCurrentPlaceholder(prev => (prev + 1) % placeholders.length)
    }, 3000)
  }
  const handleVisibilityChange = () => {
    if (document.visibilityState !== 'visible' && intervalRef.current) {
      clearInterval(intervalRef.current) // Clear the interval when the tab is not visible
      intervalRef.current = null
    }
    else if (document.visibilityState === 'visible') {
      startAnimation() // Restart the interval when the tab becomes visible
    }
  }

  const handleInput = () => {
    if (editorRef.current) {
      const newContent = editorRef.current.textContent || ''
      setContent(newContent)
      onChange?.(newContent)
    }
  }

  const handleSubmit = () => {
    if (isAsking)
      return
    if (checkAuth()) {
      if (content.trim()) {
        onSubmit?.(content.trim())
        setContent('')
        if (editorRef.current) {
          editorRef.current.textContent = ''
        }
      }
    }
  }

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleSubmit()
    }
    else if (e.key === 'Backspace' && !content) {
      e.preventDefault() // 防止删除最后一个字符后继续删除
    }
  }
  const handleCloseLoginModal = () => {
    isOpenLoginModalActions.setLeft()
  }
  const handlePaste = (event: React.ClipboardEvent<HTMLDivElement>) => {
    event.preventDefault()
    const text = event.clipboardData.getData('text/plain')
    document.execCommand('insertText', false, text)
  }

  useEffect(() => {
    startAnimation()
    document.addEventListener('visibilitychange', handleVisibilityChange)
    if (editorRef.current) {
      editorRef.current.style.height = 'auto'
      editorRef.current.style.height = `${editorRef.current.scrollHeight}px`
    }
    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current)
      }
      document.removeEventListener('visibilitychange', handleVisibilityChange)
      // console.log(isAsking, 'isAskingisAsking')
      // if (isAsking) {
      //   dispatch(setIsAsking(false))
      // }
    }
  }, [content])
  return (
    <div className="flex items-end w-full h-auto relative mx-auto bg-white  rounded-[36px] overflow-hidden transition duration-200 py-[8px] pl-[12px] pr-[12px] sm:py-[12px] sm:pl-[32px] sm:pr-[20px]">
      <div
        ref={editorRef}
        contentEditable
        translate="no"
        className="w-full min-h-[40px] max-h-[200px] p-2  rounded overflow-y-auto outline-none"
        onInput={handleInput}
        onFocus={onFocus}
        onKeyDown={handleKeyDown}
        onPaste={handlePaste}
        suppressContentEditableWarning={true}
        style={{
          resize: 'none',
        }}
      />
      <Button onClick={handleSubmit} radius="full" isDisabled={!content || isAsking} isIconOnly color="primary">
        <SendIcon />
      </Button>

      <div className="absolute inset-0 flex items-center rounded-full pointer-events-none">
        <AnimatePresence mode="wait">
          {!content && (
            <motion.p
              initial={{
                y: 5,
                opacity: 0,
              }}
              key={`current-placeholder-${currentPlaceholder}`}
              animate={{
                y: 0,
                opacity: 1,
              }}
              exit={{
                y: -15,
                opacity: 0,
              }}
              transition={{
                duration: 0.3,
                ease: 'linear',
              }}
              className="dark:text-zinc-500 text-[12px] sm:text-base font-normal text-[#3333334d] pl-4 sm:pl-12 text-left w-[calc(100%-2rem)] truncate"
            >
              {placeholders[currentPlaceholder]}
            </motion.p>
          )}
        </AnimatePresence>
      </div>
      <LoginModal onClose={handleCloseLoginModal} isOpen={isOpenLoginModal} />
    </div>
  )
}

export const ChatEditor = withAuth(ChatEditorBase)
