import { useState, useRef, useEffect, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { MessageSquare, Send, Loader2, X, Plus, Bot, User } from 'lucide-react'
import ReactMarkdown from 'react-markdown'
import {
  sendChatMessage,
  getChatSessions,
  getSessionMessages,
  deleteChatSession,
  type ChatMessage,
  type ChatSession,
} from '../../api/chat'

interface ChatPanelProps {
  open: boolean
  onClose: () => void
  contextType?: string
  contextId?: string
}

export default function ChatPanel({ open, onClose, contextType, contextId }: ChatPanelProps) {
  const [messages, setMessages] = useState<ChatMessage[]>([])
  const [sessionId, setSessionId] = useState<string | undefined>(() => {
    // Restore last session from localStorage
    try { return localStorage.getItem('schaeffler-chat-session') || undefined } catch { return undefined }
  })
  const [input, setInput] = useState('')
  const [showSessions, setShowSessions] = useState(false)

  // Persist sessionId to localStorage
  useEffect(() => {
    try {
      if (sessionId) localStorage.setItem('schaeffler-chat-session', sessionId)
      else localStorage.removeItem('schaeffler-chat-session')
    } catch { /* ignore */ }
  }, [sessionId])
  const messagesEndRef = useRef<HTMLDivElement>(null)
  const inputRef = useRef<HTMLInputElement>(null)
  const queryClient = useQueryClient()
  const navigate = useNavigate()

  // Load sessions
  const { data: sessions } = useQuery({
    queryKey: ['chat-sessions'],
    queryFn: getChatSessions,
    enabled: open,
    staleTime: 30_000,
  })

  // Load messages when session changes
  const { data: sessionMessages } = useQuery({
    queryKey: ['chat-messages', sessionId],
    queryFn: () => getSessionMessages(sessionId!),
    enabled: !!sessionId && open,
    staleTime: 10_000,
  })

  useEffect(() => {
    if (sessionMessages) {
      setMessages(sessionMessages)
    }
  }, [sessionMessages])

  // Scroll to bottom when messages change
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }, [messages])

  // Focus input when panel opens
  useEffect(() => {
    if (open) {
      setTimeout(() => inputRef.current?.focus(), 200)
    }
  }, [open])

  // Send message mutation
  const sendMut = useMutation({
    mutationFn: (message: string) =>
      sendChatMessage(message, sessionId, contextType, contextId),
    onSuccess: (data) => {
      setSessionId(data.session_id)
      setMessages((prev) => [...prev, data.user_message, data.assistant_message])
      queryClient.invalidateQueries({ queryKey: ['chat-sessions'] })
    },
  })

  const handleSend = useCallback(() => {
    const trimmed = input.trim()
    if (!trimmed || sendMut.isPending) return
    setInput('')
    sendMut.mutate(trimmed)
  }, [input, sendMut])

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

  const handleNewChat = () => {
    setSessionId(undefined)
    setMessages([])
    setShowSessions(false)
    inputRef.current?.focus()
  }

  const handleSelectSession = (session: ChatSession) => {
    setSessionId(session.session_id)
    setShowSessions(false)
  }

  const handleDeleteSession = async (sid: string, e: React.MouseEvent) => {
    e.stopPropagation()
    await deleteChatSession(sid)
    queryClient.invalidateQueries({ queryKey: ['chat-sessions'] })
    if (sid === sessionId) {
      handleNewChat()
    }
  }

  const formatTime = (iso: string) => {
    const d = new Date(iso)
    return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
  }

  if (!open) return null

  return (
    <div
      className="fixed right-0 top-0 h-full w-96 z-40 flex flex-col border-l border-border-default shadow-xl"
      style={{
        backgroundColor: 'var(--color-bg-surface)',
        animation: 'slideInRight 0.25s ease-out',
      }}
    >
      {/* Inline keyframes for slide animation */}
      <style>{`
        @keyframes slideInRight {
          from { transform: translateX(100%); }
          to { transform: translateX(0); }
        }
        @keyframes typingDot {
          0%, 60%, 100% { opacity: 0.3; transform: translateY(0); }
          30% { opacity: 1; transform: translateY(-4px); }
        }
      `}</style>

      {/* Header */}
      <div
        className="flex items-center gap-2 px-4 py-3 border-b border-border-default shrink-0"
        style={{ backgroundColor: 'var(--color-bg-surface)' }}
      >
        <Bot size={20} className="text-accent" />
        <button
          onClick={() => setShowSessions((v) => !v)}
          className="flex-1 text-left text-sm font-semibold text-content hover:text-accent transition-colors"
        >
          HartBOT
        </button>
        <button
          onClick={handleNewChat}
          className="p-1.5 rounded-md text-content-secondary hover:bg-surface-hover transition-colors"
          title="New Chat"
        >
          <Plus size={16} />
        </button>
        <button
          onClick={onClose}
          className="p-1.5 rounded-md text-content-secondary hover:bg-surface-hover transition-colors"
          title="Close"
        >
          <X size={16} />
        </button>
      </div>

      {/* Session list dropdown */}
      {showSessions && sessions && sessions.length > 0 && (
        <div
          className="border-b border-border-default max-h-48 overflow-y-auto"
          style={{ backgroundColor: 'var(--color-bg-surface-alt)' }}
        >
          {sessions.map((s) => (
            <div
              key={s.session_id}
              onClick={() => handleSelectSession(s)}
              className="flex items-center gap-2 px-4 py-2 cursor-pointer hover:bg-surface-hover transition-colors"
              style={s.session_id === sessionId ? { backgroundColor: 'var(--color-bg-accent-light)' } : undefined}
            >
              <MessageSquare size={14} className="text-content-muted shrink-0" />
              <div className="flex-1 min-w-0">
                <p className="text-xs text-content truncate">{s.last_message}</p>
                <p className="text-[10px] text-content-muted">
                  {s.message_count} messages
                </p>
              </div>
              <button
                onClick={(e) => handleDeleteSession(s.session_id, e)}
                className="p-1 rounded text-content-muted hover:text-red-500 transition-colors shrink-0"
                title="Delete session"
              >
                <X size={12} />
              </button>
            </div>
          ))}
        </div>
      )}

      {/* Messages */}
      <div className="flex-1 overflow-y-auto px-4 py-3 space-y-3">
        {messages.length === 0 && !sendMut.isPending && (
          <div className="flex flex-col items-center justify-center h-full text-content-muted">
            <Bot size={40} className="mb-3 opacity-30" />
            <p className="text-sm">Ask me anything about your orders, products, or renders.</p>
          </div>
        )}

        {messages.map((msg) => (
          <div
            key={msg.id}
            className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}
            style={{ animation: 'fadeIn 0.2s ease-out' }}
          >
            <div className="flex gap-2 max-w-[85%]">
              {msg.role === 'assistant' && (
                <div
                  className="w-6 h-6 rounded-full flex items-center justify-center shrink-0 mt-1"
                  style={{ backgroundColor: 'var(--color-bg-accent-light)' }}
                >
                  <Bot size={14} className="text-accent" />
                </div>
              )}
              <div>
                <div
                  className={`px-3 py-2 text-sm leading-relaxed ${
                    msg.role === 'user'
                      ? 'rounded-2xl rounded-br-md'
                      : 'rounded-2xl rounded-bl-md'
                  }`}
                  style={
                    msg.role === 'user'
                      ? { backgroundColor: 'var(--color-bg-accent)', color: 'var(--color-text-accent-text)' }
                      : { backgroundColor: 'var(--color-bg-surface-hover)', color: 'var(--color-text-content)' }
                  }
                >
                  {msg.role === 'assistant' ? (
                    <ReactMarkdown
                      components={{
                        p: ({ children }) => <p className="mb-1 last:mb-0">{children}</p>,
                        strong: ({ children }) => <strong className="font-semibold">{children}</strong>,
                        ul: ({ children }) => <ul className="list-disc list-inside mb-1 space-y-0.5">{children}</ul>,
                        ol: ({ children }) => <ol className="list-decimal list-inside mb-1 space-y-0.5">{children}</ol>,
                        li: ({ children }) => <li>{children}</li>,
                        code: ({ children }) => <code className="px-1 py-0.5 rounded text-xs font-mono" style={{ backgroundColor: 'var(--color-bg-muted)' }}>{children}</code>,
                        a: ({ href, children }) => {
                          const isInternal = href?.startsWith('/products/') || href?.startsWith('/orders/')
                          if (isInternal) {
                            return <a href={href} onClick={(e) => { e.preventDefault(); navigate(href!) }} className="text-accent underline hover:text-accent-hover cursor-pointer">{children}</a>
                          }
                          return <a href={href} target="_blank" rel="noopener noreferrer" className="text-accent underline hover:text-accent-hover">{children}</a>
                        },
                        img: ({ src, alt }) => <img src={src} alt={alt || 'render'} className="max-w-full rounded-lg mt-1 mb-1 border border-border-default" style={{ maxHeight: '200px' }} />,
                      }}
                    >
                      {msg.content}
                    </ReactMarkdown>
                  ) : (
                    msg.content
                  )}
                </div>
                <p className="text-[10px] text-content-muted mt-0.5 px-1">
                  {formatTime(msg.created_at)}
                </p>
              </div>
              {msg.role === 'user' && (
                <div
                  className="w-6 h-6 rounded-full flex items-center justify-center shrink-0 mt-1"
                  style={{ backgroundColor: 'var(--color-bg-accent)' }}
                >
                  <User size={14} style={{ color: 'var(--color-text-accent-text)' }} />
                </div>
              )}
            </div>
          </div>
        ))}

        {/* Typing indicator */}
        {sendMut.isPending && (
          <div className="flex justify-start">
            <div className="flex gap-2 items-center">
              <div
                className="w-6 h-6 rounded-full flex items-center justify-center shrink-0"
                style={{ backgroundColor: 'var(--color-bg-accent-light)' }}
              >
                <Bot size={14} className="text-accent" />
              </div>
              <div
                className="px-4 py-2.5 rounded-2xl rounded-bl-md flex gap-1"
                style={{ backgroundColor: 'var(--color-bg-surface-hover)' }}
              >
                {[0, 1, 2].map((i) => (
                  <span
                    key={i}
                    className="w-1.5 h-1.5 rounded-full bg-content-muted"
                    style={{
                      animation: `typingDot 1.4s ease-in-out ${i * 0.2}s infinite`,
                    }}
                  />
                ))}
              </div>
            </div>
          </div>
        )}

        {/* Error state */}
        {sendMut.isError && (
          <div className="flex justify-center">
            <p className="text-xs text-red-500 bg-red-50 px-3 py-1.5 rounded-full">
              Failed to send. Please try again.
            </p>
          </div>
        )}

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

      {/* Input area */}
      <div className="px-4 py-3 border-t border-border-default shrink-0">
        <div className="flex items-center gap-2">
          <input
            ref={inputRef}
            type="text"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="Type a message..."
            disabled={sendMut.isPending}
            className="flex-1 text-sm px-3 py-2 rounded-lg border border-border-default bg-surface text-content placeholder-content-muted focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent disabled:opacity-50"
          />
          <button
            onClick={handleSend}
            disabled={!input.trim() || sendMut.isPending}
            className="p-2 rounded-lg bg-accent text-accent-text hover:bg-accent-hover disabled:opacity-40 transition-colors"
          >
            {sendMut.isPending ? (
              <Loader2 size={18} className="animate-spin" />
            ) : (
              <Send size={18} />
            )}
          </button>
        </div>
      </div>
    </div>
  )
}
