import { useRef, useState, useEffect } from 'react'
import { useMutation } from '@tanstack/react-query'
import { IconSend, IconRobot, IconUser } from '@tabler/icons-react'
import { api, type ChatMessage, type AssistantReply } from '../lib/api'
import { useLang } from '../i18n/LanguageContext'
import { PageHeader } from '../components/PageHeader'

interface UiMessage extends ChatMessage {
  reply?: AssistantReply
}

export function Assistant() {
  const { t } = useLang()
  const [input, setInput] = useState('')
  const [messages, setMessages] = useState<UiMessage[]>([])
  const scrollRef = useRef<HTMLDivElement>(null)

  const mutation = useMutation({
    mutationFn: (history: ChatMessage[]) => api.chat(history),
    onSuccess: (reply) => {
      setMessages((prev) => [
        ...prev,
        { role: 'assistant', content: reply.content, reply },
      ])
    },
    onError: () => {
      setMessages((prev) => [
        ...prev,
        {
          role: 'assistant',
          content: 'Klaida kreipiantis į mazgo API. / Error reaching the node API.',
        },
      ])
    },
  })

  useEffect(() => {
    scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' })
  }, [messages, mutation.isPending])

  function send() {
    const text = input.trim()
    if (!text || mutation.isPending) return
    const next: UiMessage[] = [...messages, { role: 'user', content: text }]
    setMessages(next)
    setInput('')
    mutation.mutate(next.map(({ role, content }) => ({ role, content })))
  }

  return (
    <div className="flex h-[calc(100vh-8.5rem)] flex-col">
      <PageHeader title={t('ai.title')} subtitle={t('ai.subtitle')} />

      <div
        ref={scrollRef}
        className="flex-1 space-y-4 overflow-y-auto rounded-xl border border-arka-border bg-arka-surface p-4"
      >
        {messages.length === 0 && (
          <div className="flex items-start gap-3 text-sm text-arka-muted">
            <Avatar role="assistant" />
            <div className="rounded-lg bg-arka-surface-2 px-3 py-2">{t('ai.intro')}</div>
          </div>
        )}

        {messages.map((m, i) => (
          <Bubble key={i} message={m} />
        ))}

        {mutation.isPending && (
          <div className="flex items-start gap-3 text-sm text-arka-muted">
            <Avatar role="assistant" />
            <div className="rounded-lg bg-arka-surface-2 px-3 py-2">{t('ai.thinking')}</div>
          </div>
        )}
      </div>

      <p className="mt-2 text-center text-[11px] text-arka-muted">⚠ {t('ai.warning')}</p>

      <div className="mt-2 flex gap-2">
        <textarea
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
              e.preventDefault()
              send()
            }
          }}
          rows={1}
          placeholder={t('ai.placeholder')}
          className="flex-1 resize-none rounded-lg border border-arka-border bg-arka-surface px-3 py-2.5 text-sm text-arka-text placeholder:text-arka-muted focus:border-arka-accent focus:outline-none"
        />
        <button
          onClick={send}
          disabled={mutation.isPending}
          className="flex items-center gap-2 rounded-lg bg-arka-accent px-4 text-sm font-semibold text-arka-bg transition-opacity hover:opacity-90 disabled:opacity-50"
        >
          <IconSend size={18} />
          {t('ai.send')}
        </button>
      </div>
    </div>
  )
}

function Avatar({ role }: { role: ChatMessage['role'] }) {
  const isUser = role === 'user'
  return (
    <div
      className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${
        isUser ? 'bg-arka-surface-2 text-arka-text' : 'bg-arka-accent/15 text-arka-accent'
      }`}
    >
      {isUser ? <IconUser size={18} /> : <IconRobot size={18} />}
    </div>
  )
}

function Bubble({ message }: { message: UiMessage }) {
  const { t } = useLang()
  const isUser = message.role === 'user'
  return (
    <div className={`flex items-start gap-3 ${isUser ? 'flex-row-reverse' : ''}`}>
      <Avatar role={message.role} />
      <div className={`max-w-[80%] ${isUser ? 'text-right' : ''}`}>
        <div
          className={`whitespace-pre-wrap rounded-lg px-3 py-2 text-sm ${
            isUser
              ? 'bg-arka-accent/15 text-arka-text'
              : 'bg-arka-surface-2 text-arka-text'
          }`}
        >
          {message.content}
        </div>
        {message.reply && (
          <div className="mt-1.5 flex flex-wrap items-center gap-1.5 text-[11px]">
            <span
              className={`rounded px-1.5 py-0.5 ${
                message.reply.mode === 'llm'
                  ? 'bg-arka-online/15 text-arka-online'
                  : 'bg-arka-degraded/15 text-arka-degraded'
              }`}
            >
              {message.reply.mode === 'llm' ? t('ai.llmBadge') : t('ai.fallbackBadge')}
            </span>
            {message.reply.sources.length > 0 && (
              <span className="text-arka-muted">
                {t('ai.sources')}: {message.reply.sources.map((s) => s.title).join(', ')}
              </span>
            )}
          </div>
        )}
      </div>
    </div>
  )
}
