'use client'

import { useState, useRef, useEffect, useCallback } from 'react'
import {
  MessageSquare,
  Send,
  Plus,
  Copy,
  Check,
  FileDown,
  Loader2,
  Brain,
  Sparkles,
  Trash2,
  Clock,
  FileText,
} from 'lucide-react'
import ReactMarkdown from 'react-markdown'
import { stripMarkdown, downloadAsWord } from '@/lib/utils'

// ─── Types ───────────────────────────────────────────────────────

interface ChatMessage {
  id: string
  role: 'USER' | 'ASSISTANT'
  content: string
  createdAt: string
}

interface ChatSummary {
  id: string
  title: string
  createdAt: string
  messages: { content: string; createdAt: string }[]
}

// ─── Suggested Questions ─────────────────────────────────────────

const SUGGESTED_QUESTIONS = [
  {
    text: 'Qual o prazo para contestação no JEC?',
    icon: '⚖️',
    area: 'Processual Civil',
  },
  {
    text: 'Como funciona o recurso de apelação?',
    icon: '📋',
    area: 'Recursos',
  },
  {
    text: 'Quais os requisitos do habeas corpus?',
    icon: '🔓',
    area: 'Penal',
  },
]

// ─── Component ───────────────────────────────────────────────────

export default function ChatPage() {
  const [chats, setChats] = useState<ChatSummary[]>([])
  const [activeChatId, setActiveChatId] = useState<string | null>(null)
  const [messages, setMessages] = useState<ChatMessage[]>([])
  const [input, setInput] = useState('')
  const [isStreaming, setIsStreaming] = useState(false)
  const [copiedId, setCopiedId] = useState<string | null>(null)
  const [loadingChats, setLoadingChats] = useState(true)
  const [sidebarOpen, setSidebarOpen] = useState(true)
  const [downloadingId, setDownloadingId] = useState<string | null>(null)

  const messagesEndRef = useRef<HTMLDivElement>(null)
  const inputRef = useRef<HTMLTextAreaElement>(null)

  // Delete chat
  async function deleteChat(chatId: string) {
    if (!confirm('Tem certeza que deseja apagar esta conversa?')) return
    try {
      const res = await fetch(`/api/chat/${chatId}`, { method: 'DELETE' })
      if (res.ok) {
        setChats((prev) => prev.filter((c) => c.id !== chatId))
        if (activeChatId === chatId) {
          setActiveChatId(null)
          setMessages([])
        }
      }
    } catch (err) {
      console.error('Error deleting chat:', err)
    }
  }

  // Auto-scroll to bottom
  const scrollToBottom = useCallback(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }, [])

  useEffect(() => {
    scrollToBottom()
  }, [messages, scrollToBottom])

  // Load chat list
  useEffect(() => {
    fetchChats()
  }, [])

  async function fetchChats() {
    try {
      const res = await fetch('/api/chat')
      if (res.ok) {
        const data = await res.json()
        setChats(data.chats || [])
      }
    } catch (e) {
      console.error('Failed to load chats:', e)
    } finally {
      setLoadingChats(false)
    }
  }

  // Load messages for a chat
  async function loadChat(chatId: string) {
    setActiveChatId(chatId)
    try {
      const res = await fetch(`/api/chat/${chatId}`)
      if (res.ok) {
        const data = await res.json()
        setMessages(data.messages || [])
      }
    } catch {
      setMessages([])
    }
  }

  // New chat
  function handleNewChat() {
    setActiveChatId(null)
    setMessages([])
    setInput('')
    inputRef.current?.focus()
  }

  // Send message
  async function handleSend(text?: string) {
    const messageText = (text || input).trim()
    if (!messageText || isStreaming) return

    setInput('')
    setIsStreaming(true)

    // Optimistic: add user message
    const userMsg: ChatMessage = {
      id: `temp-${Date.now()}`,
      role: 'USER',
      content: messageText,
      createdAt: new Date().toISOString(),
    }
    setMessages((prev) => [...prev, userMsg])

    // Placeholder for assistant
    const assistantId = `assistant-${Date.now()}`
    const assistantMsg: ChatMessage = {
      id: assistantId,
      role: 'ASSISTANT',
      content: '',
      createdAt: new Date().toISOString(),
    }
    setMessages((prev) => [...prev, assistantMsg])

    try {
      const res = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          message: messageText,
          chatId: activeChatId || undefined,
        }),
      })

      if (!res.ok) {
        const errData = await res.json().catch(() => ({}))
        throw new Error(errData.error || 'Erro ao enviar mensagem')
      }

      // Read SSE stream
      const reader = res.body!.getReader()
      const decoder = new TextDecoder()
      let buffer = ''
      let fullContent = ''
      let receivedChatId: string | null = null

      while (true) {
        const { done, value } = await reader.read()
        if (done) break

        buffer += decoder.decode(value, { stream: true })
        const lines = buffer.split('\n')
        buffer = lines.pop() || ''

        for (const line of lines) {
          if (!line.startsWith('data: ')) continue
          const data = line.slice(6).trim()
          if (data === '[DONE]') continue

          try {
            const parsed = JSON.parse(data)

            if (parsed.chatId && !receivedChatId) {
              receivedChatId = parsed.chatId
              if (!activeChatId) {
                setActiveChatId(receivedChatId)
              }
            }

            if (parsed.token) {
              fullContent += parsed.token
              setMessages((prev) =>
                prev.map((m) =>
                  m.id === assistantId ? { ...m, content: fullContent } : m
                )
              )
            }
          } catch {
            // skip malformed
          }
        }
      }

      // Refresh chat list
      fetchChats()
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : 'Erro desconhecido'
      setMessages((prev) =>
        prev.map((m) =>
          m.id === assistantId
            ? { ...m, content: `⚠️ ${errMsg}. Tente novamente.` }
            : m
        )
      )
    } finally {
      setIsStreaming(false)
    }
  }

  // Copy message - strips markdown formatting
  function handleCopy(content: string, id: string) {
    navigator.clipboard.writeText(stripMarkdown(content))
    setCopiedId(id)
    setTimeout(() => setCopiedId(null), 2000)
  }

  // Download as Word
  async function handleDownloadWord(content: string, id: string) {
    setDownloadingId(id)
    try {
      await downloadAsWord('Resposta Chat IA', content)
    } catch (err) {
      console.error('Download error:', err)
    } finally {
      setDownloadingId(null)
    }
  }

  // Format date
  function formatDate(dateStr: string) {
    const d = new Date(dateStr)
    const now = new Date()
    const diff = now.getTime() - d.getTime()
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))

    if (days === 0) return 'Hoje'
    if (days === 1) return 'Ontem'
    if (days < 7) return `${days} dias atrás`
    return d.toLocaleDateString('pt-BR', { day: '2-digit', month: 'short' })
  }

  // Keyboard handler
  function handleKeyDown(e: React.KeyboardEvent<HTMLTextAreaElement>) {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleSend()
    }
  }

  // Auto-resize textarea
  function handleInputChange(e: React.ChangeEvent<HTMLTextAreaElement>) {
    setInput(e.target.value)
    const el = e.target
    el.style.height = 'auto'
    el.style.height = Math.min(el.scrollHeight, 160) + 'px'
  }

  return (
    <div className="-mx-4 -my-6 sm:-mx-6 lg:-mx-8 flex h-[calc(100vh-3.5rem)] lg:h-screen">
      {/* ─── Chat Sidebar ─── */}
      <aside
        className={`
          ${sidebarOpen ? 'w-72' : 'w-0 overflow-hidden'}
          flex-shrink-0 border-r border-white/5 bg-[#070b14] transition-all duration-300
          flex flex-col
        `}
      >
        {/* New Chat Button */}
        <div className="p-3 border-b border-white/5">
          <button
            onClick={handleNewChat}
            className="flex w-full items-center gap-2 rounded-xl bg-teal-600 px-4 py-2.5 text-sm font-semibold text-white transition-all hover:bg-teal-500 hover:shadow-lg hover:shadow-teal-500/20"
          >
            <Plus className="h-4 w-4" />
            Nova Conversa
          </button>
        </div>

        {/* Chat List */}
        <div className="flex-1 overflow-y-auto px-2 py-2">
          {loadingChats ? (
            <div className="flex items-center justify-center py-8">
              <Loader2 className="h-5 w-5 animate-spin text-teal-400" />
            </div>
          ) : chats.length === 0 ? (
            <div className="px-3 py-8 text-center">
              <MessageSquare className="mx-auto h-8 w-8 text-zinc-600" />
              <p className="mt-2 text-xs text-zinc-500">Nenhuma conversa ainda</p>
            </div>
          ) : (
            <div className="space-y-0.5">
              {chats.map((chat) => (
                <button
                  key={chat.id}
                  onClick={() => loadChat(chat.id)}
                  className={`
                    group flex w-full items-start gap-2 rounded-lg px-3 py-2.5 text-left
                    transition-all duration-150
                    ${
                      activeChatId === chat.id
                        ? 'bg-teal-600/15 text-teal-300'
                        : 'text-zinc-400 hover:bg-white/5 hover:text-zinc-200'
                    }
                  `}
                >
                  <MessageSquare className="mt-0.5 h-4 w-4 flex-shrink-0 opacity-50" />
                  <div className="flex-1 overflow-hidden">
                    <p className="truncate text-sm font-medium">{chat.title}</p>
                    <p className="mt-0.5 flex items-center gap-1 text-[10px] text-zinc-600">
                      <Clock className="h-2.5 w-2.5" />
                      {formatDate(chat.createdAt)}
                    </p>
                  </div>
                  <button
                    onClick={(e) => {
                      e.stopPropagation()
                      deleteChat(chat.id)
                    }}
                    className="mt-0.5 hidden rounded p-1 text-zinc-500 transition-colors hover:bg-red-500/20 hover:text-red-400 group-hover:block"
                    title="Apagar conversa"
                  >
                    <Trash2 className="h-3.5 w-3.5" />
                  </button>
                </button>
              ))}
            </div>
          )}
        </div>
      </aside>

      {/* ─── Chat Main Area ─── */}
      <div className="flex flex-1 flex-col overflow-hidden bg-[#0a0f1a]">
        {/* Header */}
        <div className="flex items-center gap-3 border-b border-white/5 bg-[#0a0f1a]/80 px-4 py-3 backdrop-blur-md">
          <button
            onClick={() => setSidebarOpen(!sidebarOpen)}
            className="rounded-lg p-1.5 text-zinc-400 hover:bg-white/5 hover:text-white"
            title={sidebarOpen ? 'Fechar sidebar' : 'Abrir sidebar'}
          >
            <MessageSquare className="h-5 w-5" />
          </button>
          <div className="flex items-center gap-2">
            <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-teal-600/20">
              <Brain className="h-4 w-4 text-teal-400" />
            </div>
            <div>
              <h1 className="text-sm font-semibold text-white">Chat IA</h1>
              <p className="text-[10px] text-zinc-500">Assistente especialista em Direito brasileiro</p>
            </div>
          </div>
        </div>

        {/* Messages Area */}
        <div className="flex-1 overflow-y-auto">
          {messages.length === 0 ? (
            /* ─── Welcome Screen ─── */
            <div className="flex h-full flex-col items-center justify-center px-4">
              <div className="mb-6 flex h-16 w-16 items-center justify-center rounded-2xl bg-teal-600/20 ring-1 ring-teal-500/30">
                <Brain className="h-8 w-8 text-teal-400" />
              </div>
              <h2 className="text-xl font-bold text-white">Chat IA</h2>
              <p className="mt-2 max-w-md text-center text-sm text-zinc-500">
                Converse com um assistente especialista em Direito brasileiro.
                Tire dúvidas sobre legislação, jurisprudência e doutrina.
              </p>

              {/* Suggested Questions */}
              <div className="mt-8 grid w-full max-w-2xl gap-3 sm:grid-cols-3">
                {SUGGESTED_QUESTIONS.map((q) => (
                  <button
                    key={q.text}
                    onClick={() => handleSend(q.text)}
                    disabled={isStreaming}
                    className="group flex flex-col gap-2 rounded-xl border border-white/5 bg-white/[0.02] p-4 text-left transition-all hover:border-teal-500/30 hover:bg-teal-600/5"
                  >
                    <div className="flex items-center gap-2">
                      <span className="text-lg">{q.icon}</span>
                      <span className="text-[10px] font-medium uppercase tracking-wider text-teal-400/60">
                        {q.area}
                      </span>
                    </div>
                    <p className="text-sm text-zinc-300 group-hover:text-white">
                      {q.text}
                    </p>
                  </button>
                ))}
              </div>

              <div className="mt-8 flex items-center gap-2 text-[10px] text-zinc-600">
                <Sparkles className="h-3 w-3" />
                Respostas baseadas na legislação vigente e jurisprudência dos tribunais superiores
              </div>
            </div>
          ) : (
            /* ─── Message List ─── */
            <div className="mx-auto max-w-3xl px-4 py-6 space-y-6">
              {messages.map((msg) => (
                <div
                  key={msg.id}
                  className={`flex gap-3 ${msg.role === 'USER' ? 'justify-end' : 'justify-start'}`}
                >
                  {msg.role === 'ASSISTANT' && (
                    <div className="flex-shrink-0 mt-1">
                      <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-teal-600/20">
                        <Brain className="h-4 w-4 text-teal-400" />
                      </div>
                    </div>
                  )}

                  <div
                    className={`group relative max-w-[85%] rounded-2xl px-4 py-3 ${
                      msg.role === 'USER'
                        ? 'bg-teal-600 text-white'
                        : 'bg-white/[0.04] text-zinc-200 border border-white/5'
                    }`}
                  >
                    {msg.role === 'ASSISTANT' ? (
                      <div className="prose prose-invert prose-sm max-w-none prose-headings:text-teal-300 prose-headings:font-semibold prose-strong:text-teal-200 prose-code:text-teal-300 prose-blockquote:border-teal-500/30 prose-blockquote:text-zinc-400 prose-a:text-teal-400 prose-li:marker:text-teal-500">
                        <ReactMarkdown>{msg.content || '▍'}</ReactMarkdown>
                      </div>
                    ) : (
                      <p className="text-sm whitespace-pre-wrap">{msg.content}</p>
                    )}

                    {/* Action buttons for assistant messages */}
                    {msg.content && msg.role === 'ASSISTANT' && (
                      <div className="absolute -bottom-8 right-0 flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                        <button
                          onClick={() => handleCopy(msg.content, msg.id)}
                          className="flex items-center gap-1 rounded-md px-2 py-1 text-[10px] text-zinc-500 hover:text-zinc-300"
                        >
                          {copiedId === msg.id ? (
                            <>
                              <Check className="h-3 w-3 text-green-400" />
                              <span className="text-green-400">Copiado</span>
                            </>
                          ) : (
                            <>
                              <Copy className="h-3 w-3" />
                              Copiar
                            </>
                          )}
                        </button>
                        <button
                          onClick={() => handleDownloadWord(msg.content, msg.id)}
                          disabled={downloadingId === msg.id}
                          className="flex items-center gap-1 rounded-md px-2 py-1 text-[10px] text-zinc-500 hover:text-zinc-300"
                        >
                          {downloadingId === msg.id ? (
                            <Loader2 className="h-3 w-3 animate-spin" />
                          ) : (
                            <FileText className="h-3 w-3" />
                          )}
                          Word
                        </button>
                      </div>
                    )}

                    {/* Copy button for user messages */}
                    {msg.content && msg.role === 'USER' && (
                      <button
                        onClick={() => handleCopy(msg.content, msg.id)}
                        className="absolute -bottom-8 right-0 flex items-center gap-1 rounded-md px-2 py-1 text-[10px] text-zinc-500 opacity-0 transition-opacity group-hover:opacity-100 hover:text-zinc-300"
                      >
                        {copiedId === msg.id ? (
                          <>
                            <Check className="h-3 w-3 text-green-400" />
                            <span className="text-green-400">Copiado</span>
                          </>
                        ) : (
                          <>
                            <Copy className="h-3 w-3" />
                            Copiar
                          </>
                        )}
                      </button>
                    )}
                  </div>

                  {msg.role === 'USER' && (
                    <div className="flex-shrink-0 mt-1">
                      <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-teal-600/40 text-xs font-bold text-white">
                        Vc
                      </div>
                    </div>
                  )}
                </div>
              ))}

              {isStreaming && (
                <div className="flex items-center gap-2 px-11 text-xs text-teal-400/60">
                  <Loader2 className="h-3 w-3 animate-spin" />
                  Gerando resposta...
                </div>
              )}

              <div ref={messagesEndRef} />
            </div>
          )}
        </div>

        {/* ─── Input Area ─── */}
        <div className="border-t border-white/5 bg-[#0a0f1a]/80 px-4 py-3 backdrop-blur-md">
          <div className="mx-auto max-w-3xl">
            <div className="flex items-end gap-2 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-2 transition-colors focus-within:border-teal-500/40">
              <textarea
                ref={inputRef}
                value={input}
                onChange={handleInputChange}
                onKeyDown={handleKeyDown}
                placeholder="Digite sua pergunta jurídica..."
                disabled={isStreaming}
                rows={1}
                className="flex-1 resize-none bg-transparent text-sm text-white placeholder-zinc-500 outline-none disabled:opacity-50"
                style={{ maxHeight: '160px' }}
              />
              <button
                onClick={() => handleSend()}
                disabled={!input.trim() || isStreaming}
                className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg bg-teal-600 text-white transition-all hover:bg-teal-500 disabled:opacity-30 disabled:hover:bg-teal-600"
              >
                {isStreaming ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                  <Send className="h-4 w-4" />
                )}
              </button>
            </div>
            <p className="mt-2 text-center text-[10px] text-zinc-600">
              IA pode gerar informações imprecisas. Verifique sempre com a legislação vigente.
            </p>
          </div>
        </div>
      </div>
    </div>
  )
}
