import { useEffect, useRef } from 'react'
import { Link } from 'react-router-dom'
import { Button, ErrorText } from '../ui'
import { IslanderAvatar } from './IslanderAvatar'
import { IslanderMarkdown } from './IslanderMarkdown'

export type IslanderChatMessage = {
  id: string
  role: 'user' | 'assistant' | 'system'
  content: string
}

type IslanderChatPanelProps = {
  messages: IslanderChatMessage[]
  input: string
  streaming: boolean
  acting?: boolean
  error: string
  aiReady: boolean
  suggestions: string[]
  onInputChange: (value: string) => void
  onSend: () => void
  onSuggestion: (text: string) => void
  onClose: () => void
}

export function IslanderChatPanel({
  messages,
  input,
  streaming,
  acting = false,
  error,
  aiReady,
  suggestions,
  onInputChange,
  onSend,
  onSuggestion,
  onClose,
}: IslanderChatPanelProps) {
  const endRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    endRef.current?.scrollIntoView({ behavior: 'smooth', block: 'end' })
  }, [messages, streaming, acting])

  const busy = streaming || acting
  const canSend = aiReady && !busy && input.trim().length > 0

  return (
    <div className="ac-islander-panel auth-ticket ac-dialog-texture">
      <header className="ac-islander-panel__header">
        <div className="ac-islander-panel__header-main">
          <IslanderAvatar size="chip" className="ac-islander-panel__header-avatar" />
          <div className="min-w-0">
            <h2 className="truncate text-base font-black text-ink">島民嚮導</h2>
            <p className="truncate text-xs text-muted">巡樓站內助手</p>
          </div>
        </div>
        <button type="button" onClick={onClose} className="ac-islander-panel__close" aria-label="收合聊天">
          <span aria-hidden>×</span>
        </button>
      </header>

      <div className="ac-islander-panel__body">
        {!aiReady ? (
          <p className="ac-islander-panel__notice">
            尚未設定 AI API key。請先到{' '}
            <Link to="/settings" className="ac-link font-semibold">
              設定
            </Link>{' '}
            完成 AI 設定後再來聊。
          </p>
        ) : null}

        <div className="ac-islander-messages">
          {messages.length === 0 ? (
            <div className="ac-islander-empty">
              <IslanderAvatar className="ac-islander-empty__avatar" />
              <p className="ac-islander-empty__title">嗨，我是島民</p>
              <p className="ac-islander-empty__desc">有問題再跟我說就好。</p>
            </div>
          ) : (
            messages.map((message) => {
              if (message.role === 'system') {
                return (
                  <p key={message.id} className="ac-islander-system" aria-live="polite">
                    {message.content}
                  </p>
                )
              }

              return (
                <div
                  key={message.id}
                  className={
                    message.role === 'user'
                      ? 'ac-islander-row ac-islander-row--user'
                      : 'ac-islander-row ac-islander-row--assistant'
                  }
                >
                  {message.role === 'assistant' ? (
                    <IslanderAvatar size="chip" className="ac-islander-row__avatar" />
                  ) : null}
                  <div
                    className={
                      message.role === 'user'
                        ? 'ac-islander-bubble ac-islander-bubble--user'
                        : 'ac-islander-bubble ac-islander-bubble--assistant'
                    }
                  >
                    {message.role === 'assistant' ? (
                      message.content.trim() ? (
                        <IslanderMarkdown content={message.content} />
                      ) : streaming ? (
                        <span className="ac-islander-typing" aria-live="polite">
                          <span />
                          <span />
                          <span />
                        </span>
                      ) : null
                    ) : (
                      <p className="ac-islander-bubble__text">{message.content}</p>
                    )}
                  </div>
                </div>
              )
            })
          )}
          <div ref={endRef} className="ac-islander-messages__end" aria-hidden />
        </div>

        {suggestions.length > 0 && messages.length === 0 ? (
          <div className="ac-islander-panel__suggestions">
            {suggestions.map((item) => (
              <button
                key={item}
                type="button"
                className="ac-islander-suggestion"
                onClick={() => onSuggestion(item)}
              >
                {item}
              </button>
            ))}
          </div>
        ) : null}
      </div>

      <footer className="ac-islander-panel__footer">
        <div className="ac-islander-composer">
          <textarea
            rows={1}
            value={input}
            onChange={(e) => onInputChange(e.target.value)}
            placeholder="輸入想問的事…"
            className="ac-islander-composer__input"
            disabled={busy || !aiReady}
            onKeyDown={(e) => {
              if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault()
                if (canSend) onSend()
              }
            }}
          />
          <Button
            onClick={onSend}
            disabled={!canSend}
            className="ac-islander-composer__send"
          >
            {acting ? '操作中' : streaming ? '…' : '送'}
          </Button>
        </div>

        <ErrorText message={error} />
      </footer>
    </div>
  )
}