import React, { useRef, useState } from 'react'
import { Button, Tooltip } from '@heroui/react'
import SendIcon from '@/assets/svg/send.svg?react'
import { type WithAuthProps, withAuth } from '@/auth/withAuth'
import { useAppSelector } from '@/store/hook'
import type { RootState } from '@/store'

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

const defaultPlaceholders: string[] = []

const TacticsChatEditorBase: React.FC<TacticsChatEditorProps & WithAuthProps> = ({
  onSubmit,
  onChange,
  placeholders = defaultPlaceholders,
  initialValue = '',
  checkAuth,
}) => {
  const [content, setContent] = useState(initialValue)
  const textareaRef = useRef<HTMLTextAreaElement>(null)
  const isAsking = useAppSelector((state: RootState) => state.chat.isAsking)
  const [placeholderIndex] = useState(0)

  const currentPlaceholder = placeholders[placeholderIndex] || '输入您想问的问题吧'

  const adjustHeight = () => {
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto'
      textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`
    }
  }

  const handleChange = (value: string) => {
    setContent(value)
    onChange?.(value)
    adjustHeight()
  }

  const handleSubmit = () => {
    // eslint-disable-next-line no-console
    console.log('[TacticsChatEditor] submit click', {
      content,
      isAsking,
      hasOnSubmit: Boolean(onSubmit),
    })
    if (isAsking) {
      // eslint-disable-next-line no-console
      console.log('[TacticsChatEditor] blocked: isAsking true')
      return
    }
    const authed = checkAuth()
    // eslint-disable-next-line no-console
    console.log('[TacticsChatEditor] auth checked', { authed })
    if (!authed)
      return
    const trimmed = content.trim()
    if (!trimmed) {
      // eslint-disable-next-line no-console
      console.log('[TacticsChatEditor] blocked: empty content')
      return
    }
    // eslint-disable-next-line no-console
    console.log('[TacticsChatEditor] fire onSubmit', { trimmed, hasOnSubmit: Boolean(onSubmit) })
    try {
      onSubmit?.(trimmed)
      // eslint-disable-next-line no-console
      console.log('[TacticsChatEditor] after onSubmit')
    }
    catch (error) {
      console.error('[TacticsChatEditor] onSubmit error', error)
    }
    setContent('')
    if (textareaRef.current) {
      textareaRef.current.value = ''
      adjustHeight()
    }
  }

  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleSubmit()
    }
  }

  return (
    <div className="flex items-end w-full h-auto relative mx-auto rounded-[24px] overflow-hidden transition duration-200 py-[8px] pl-[12px] pr-[12px] bg-white border border-[#0a0a0a78] shadow-[0_8px_12px_0_rgba(235,235,235,0.30)]">
      <textarea
        ref={textareaRef}
        defaultValue={initialValue}
        className="w-full min-h-[40px] max-h-[120px] p-2 rounded overflow-y-auto outline-none resize-none"
        placeholder={currentPlaceholder}
        onChange={e => handleChange(e.target.value)}
        onKeyDown={handleKeyDown}
        rows={1}
      />
      <Tooltip
        isOpen={!content && !isAsking}
        color="foreground"
        content="请输入您的问题📖"
        placement="top-end"
      >
        <Button
          className="ask-send"
          onPress={handleSubmit}
          radius="full"
          isDisabled={!content || isAsking}
          isIconOnly
          color="primary"
        >
          <SendIcon />
        </Button>
      </Tooltip>
    </div>
  )
}

export const TacticsChatEditor = withAuth(TacticsChatEditorBase)

export default TacticsChatEditor
