"use client"

import { useState, useRef, useEffect, Fragment, forwardRef, useImperativeHandle, useCallback } from "react"
import { Send, Bot, User, AlertCircle, Sparkles, Lightbulb, Target, MessageSquare, Terminal } from "lucide-react"
import { GifPicker } from "./gif-picker"

function linkifyText(text: string) {
  const urlRegex = /(https?:\/\/[^\s<]+[^\s<.,;:!?)\]}>])/
  const parts = text.split(urlRegex)
  return parts.map((part, i) => {
    if (part.startsWith("http://") || part.startsWith("https://")) {
      return <a key={i} href={part} target="_blank" rel="noopener noreferrer" className="underline text-primary hover:text-primary/80">{part}</a>
    }
    return <Fragment key={i}>{part}</Fragment>
  })
}

function formatContent(text: string) {
  const blocks: { type: "code" | "text"; content: string }[] = []
  const regex = /```(\w*)\n?([\s\S]*?)```/g
  let last = 0
  let match: RegExpExecArray | null
  while ((match = regex.exec(text)) !== null) {
    if (match.index > last) {
      blocks.push({ type: "text", content: text.slice(last, match.index) })
    }
    blocks.push({ type: "code", content: match[2].trim() })
    last = match.index + match[0].length
  }
  if (last < text.length) {
    blocks.push({ type: "text", content: text.slice(last) })
  }
  if (blocks.length) return blocks
  return [{ type: "text" as const, content: text }]
}

function formatBullets(text: string) {
  const lines = text.split("\n")
  return lines.map((line, i) => {
    const trimmed = line.trim()
    if (trimmed.startsWith("•") || trimmed.startsWith("-")) {
      const content = trimmed.replace(/^[•\-]\s*/, "")
      return (
        <div key={i} className="flex items-start gap-2.5 my-1.5">
          <span className="w-1.5 h-1.5 bg-primary rounded-sm inline-block mt-2 flex-shrink-0" />
          <span>{linkifyText(content)}</span>
        </div>
      )
    }
    if (line === "") return <div key={i} className="h-2" />
    return <p key={i} className="my-1">{linkifyText(line)}</p>
  })
}

interface ChatMessage {
  role: "user" | "assistant"
  content: string
  gif?: {
    url: string
    previewUrl: string
    title: string
  }
}

function TypingDots() {
  return (
    <div className="flex gap-1.5 items-center h-6 px-1">
      <span className="h-2 w-2 rounded-full bg-primary/60 animate-bounce" style={{ animationDelay: "0ms" }} />
      <span className="h-2 w-2 rounded-full bg-primary/60 animate-bounce" style={{ animationDelay: "150ms" }} />
      <span className="h-2 w-2 rounded-full bg-primary/60 animate-bounce" style={{ animationDelay: "300ms" }} />
    </div>
  )
}

const suggestions = [
  { icon: Terminal, label: "Lists", query: "Show me available job lists and categories" },
  { icon: Target, label: "Leads", query: "Pull recent leads" },
  { icon: Lightbulb, label: "Tips", query: "Give me general sales tips" },
  { icon: MessageSquare, label: "Objections", query: "How do I handle common objections?" },
]

interface AIChatProps {
  onMessageSent?: (msg: string) => void
}

export const AIChat = forwardRef<{ fillInput: (text: string) => void }, AIChatProps>(({ onMessageSent }, ref) => {
  const [messages, setMessages] = useState<ChatMessage[]>([])
  const [input, setInput] = useState("")
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState("")
  const [bootState, setBootState] = useState<"booting" | "ready" | "error">("booting")
  const [showGifPicker, setShowGifPicker] = useState(false)
  const messagesEndRef = useRef<HTMLDivElement>(null)
  const textareaRef = useRef<HTMLTextAreaElement>(null)
  const containerRef = useRef<HTMLDivElement>(null)
  const hasUserMessage = messages.some(m => m.role === "user")
  const loadedFromStorage = useRef(false)

  useImperativeHandle(ref, () => ({
    fillInput(text: string) {
      setInput(text)
      setTimeout(() => textareaRef.current?.focus(), 50)
    },
  }), [])

  const handleGifSelect = useCallback((gif: { url: string; previewUrl: string; title: string }) => {
    setMessages((prev) => [...prev, { role: "user", content: gif.title || "Sent a GIF", gif }])
    setShowGifPicker(false)
  }, [])

  useEffect(() => {
    if (showGifPicker) {
      const handler = (e: MouseEvent) => {
        if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
          setShowGifPicker(false)
        }
      }
      document.addEventListener("mousedown", handler)
      return () => document.removeEventListener("mousedown", handler)
    }
  }, [showGifPicker])

  useEffect(() => {
    const saved = localStorage.getItem("ai-chat-messages")
    if (saved) {
      try {
        const parsed = JSON.parse(saved)
        if (Array.isArray(parsed) && parsed.length > 0) {
          setMessages(parsed)
          loadedFromStorage.current = true
        }
      } catch {}
    } else {
      loadedFromStorage.current = false
    }
  }, [])

  useEffect(() => {
    if (messages.length > 0) {
      localStorage.setItem("ai-chat-messages", JSON.stringify(messages))
    }
  }, [messages])

  const checkServer = useCallback(async () => {
    try {
      const res = await fetch("/api/ai/health")
      if (res.ok) {
        setBootState("ready")
        return
      }
      setTimeout(checkServer, 2000)
    } catch {
      setTimeout(checkServer, 2000)
    }
  }, [])

  useEffect(() => {
    if (loadedFromStorage.current) return
    fetch("/api/ai/jobs")
      .then((r) => r.json())
      .then((data) => {
        if (data.jobs?.length) {
          const names = data.jobs.map((j: { job_title: string }) => j.job_title)
          setMessages([
            {
              role: "assistant",
              content: `Hi! I'm your Sales AI Assistant. I can help with tips for targeting:\n\n${names.map((n: string) => `• ${n}`).join("\n")}\n\nWhat would you like to know?`,
            },
          ])
        } else {
          setMessages([
            {
              role: "assistant",
              content: "Hi! I'm your Sales AI Assistant. Ask me anything about sales strategies and prospect targeting.",
            },
          ])
        }
      })
      .catch(() => {
        setMessages([
          {
            role: "assistant",
            content: "Hi! I'm your Sales AI Assistant. Ask me anything about sales strategies and prospect targeting.",
          },
        ])
      })
    checkServer()
  }, [checkServer])

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" })
  }, [messages])

  useEffect(() => {
    if (textareaRef.current) {
      textareaRef.current.style.height = "auto"
      textareaRef.current.style.height = `${Math.min(textareaRef.current.scrollHeight, 120)}px`
    }
  }, [input])

  const sendMessage = useCallback(async (text?: string) => {
    const msg = (text || input).trim()
    if (!msg || loading) return

    setInput("")
    setError("")
    onMessageSent?.(msg)
    setMessages((prev) => [...prev, { role: "user", content: msg }])
    setLoading(true)

    try {
      const res = await fetch("/api/ai/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ message: msg }),
      })

      if (!res.ok) {
        const data = await res.json().catch(() => ({}))
        throw new Error(data.error || `Error ${res.status}`)
      }

      const data = await res.json()
      setMessages((prev) => [...prev, { role: "assistant", content: data.response }])
    } catch (err) {
      const errMsg = err instanceof Error ? err.message : "AI service unavailable"
      setError(errMsg)
      setMessages((prev) => [
        ...prev,
        { role: "assistant", content: `⚠️ Error: ${errMsg}. Make sure Ollama is running with the model loaded.` },
      ])
    } finally {
      setLoading(false)
    }
  }, [input, loading, onMessageSent])

  const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault()
      sendMessage()
    }
  }, [sendMessage])

  const handleTextareaInput = useCallback((e: React.FormEvent<HTMLTextAreaElement>) => {
    const t = e.target as HTMLTextAreaElement
    t.style.height = "auto"
    t.style.height = t.scrollHeight + "px"
  }, [])

  if (bootState === "booting") {
    return (
      <div className="flex items-center justify-center h-full">
        <style>{`
          @keyframes walk {
            0%, 100% { transform: translateX(0) translateY(0); }
            25% { transform: translateX(12px) translateY(-4px); }
            50% { transform: translateX(24px) translateY(0); }
            75% { transform: translateX(12px) translateY(-4px); }
          }
          @keyframes legLeft {
            0%, 100% { transform: rotate(-10deg); }
            50% { transform: rotate(10deg); }
          }
          @keyframes legRight {
            0%, 100% { transform: rotate(10deg); }
            50% { transform: rotate(-10deg); }
          }
          @keyframes armLeft {
            0%, 100% { transform: rotate(15deg); }
            50% { transform: rotate(-15deg); }
          }
          @keyframes armRight {
            0%, 100% { transform: rotate(-15deg); }
            50% { transform: rotate(15deg); }
          }
          @keyframes blink {
            0%, 45%, 55%, 100% { height: 4px; }
            50% { height: 1px; }
          }
          .robot-walk { animation: walk 0.6s ease-in-out infinite; }
          .robot-leg-l { transform-origin: top center; animation: legLeft 0.3s ease-in-out infinite; }
          .robot-leg-r { transform-origin: top center; animation: legRight 0.3s ease-in-out infinite; }
          .robot-arm-l { transform-origin: top center; animation: armLeft 0.3s ease-in-out infinite; }
          .robot-arm-r { transform-origin: top center; animation: armRight 0.3s ease-in-out infinite; }
          .robot-eye { animation: blink 2s ease-in-out infinite; }
        `}</style>
        <div className="flex flex-col items-center gap-5">
          <p className="text-sm text-muted-foreground animate-pulse">Servers booting...</p>
          <div className="h-[56px] w-[110px] bg-card border border-border rounded-xl flex items-center justify-center overflow-hidden">
            <div className="robot-walk relative">
              <svg width="40" height="36" viewBox="0 0 40 36" fill="none">
                <rect x="10" y="2" width="20" height="16" rx="3" fill="hsl(var(--primary))" opacity="0.9"/>
                <rect x="6" y="6" width="6" height="2" rx="1" className="robot-arm-l" fill="hsl(var(--primary))" opacity="0.7"/>
                <rect x="28" y="6" width="6" height="2" rx="1" className="robot-arm-r" fill="hsl(var(--primary))" opacity="0.7"/>
                <rect x="14" y="5" width="4" height="4" rx="1" style={{fill: "hsl(var(--background))"}}/>
                <rect x="22" y="5" width="4" height="4" rx="1" style={{fill: "hsl(var(--background))"}}/>
                <circle cx="16" cy="7" r="1.5" className="robot-eye" fill="hsl(var(--primary))"/>
                <circle cx="24" cy="7" r="1.5" className="robot-eye" fill="hsl(var(--primary))"/>
                <rect x="17" y="10" width="6" height="2" rx="1" style={{fill: "hsl(var(--background))"}}/>
                <rect x="12" y="18" width="5" height="10" rx="2" className="robot-leg-l" fill="hsl(var(--primary))" opacity="0.8"/>
                <rect x="23" y="18" width="5" height="10" rx="2" className="robot-leg-r" fill="hsl(var(--primary))" opacity="0.8"/>
              </svg>
            </div>
          </div>
        </div>
      </div>
    )
  }

  const hasMessages = messages.length > 0

  return (
    <div className="flex-1 flex flex-col min-h-0">
      <div className="flex-1 overflow-y-auto px-4 py-6" style={{ backgroundImage: "radial-gradient(circle, hsl(var(--border)) 1px, transparent 1px)", backgroundSize: "24px 24px" }}>
        <div className="max-w-3xl mx-auto space-y-6">
          {messages.map((msg, i) => (
            <div key={i}>
              {msg.role === "assistant" ? (
                <div className="flex gap-3 items-start">
                  <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-primary to-primary flex items-center justify-center text-white text-sm flex-shrink-0">
                    <Bot className="h-4 w-4" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="bg-card rounded-2xl rounded-tl-sm border border-border border-l-2 border-l-primary px-5 py-4 max-w-[85%]">
                      <div className="text-foreground text-sm leading-7 whitespace-pre-wrap">
                        {formatContent(msg.content).map((block, bi) =>
                          block.type === "code" ? (
                            <pre key={bi} className="my-1.5 p-3 rounded-lg bg-muted border border-border overflow-x-auto text-xs font-mono leading-relaxed">
                              <code>{block.content}</code>
                            </pre>
                          ) : (
                            <span key={bi}>{formatBullets(block.content)}</span>
                          )
                        )}
                      </div>
                    </div>
                    <div className="text-muted-foreground text-[10px] mt-1">AI Assistant</div>
                  </div>
                </div>
              ) : (
                <div className="flex gap-3 items-start flex-row-reverse">
                  <div className="flex-1 min-w-0 flex justify-end">
                    <div className="bg-gradient-to-br from-primary to-primary rounded-2xl rounded-tr-sm px-5 py-4 max-w-[75%]">
                      {msg.gif ? (
                        <img
                          src={msg.gif.url}
                          alt={msg.gif.title || "GIF"}
                          className="w-full rounded-lg max-h-64 object-cover"
                          loading="lazy"
                        />
                      ) : (
                        <div className="text-white text-sm leading-7 whitespace-pre-wrap">{msg.content}</div>
                      )}
                    </div>
                  </div>
                </div>
              )}
            </div>
          ))}
          {loading && (
            <div className="flex gap-3 items-start">
              <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-primary to-primary flex items-center justify-center text-white text-sm flex-shrink-0">
                <Bot className="h-4 w-4" />
              </div>
              <div className="bg-card rounded-2xl rounded-tl-sm border border-border border-l-2 border-l-primary px-5 py-4 inline-flex items-center gap-1.5">
                <TypingDots />
              </div>
            </div>
          )}
          <div ref={messagesEndRef} />
        </div>
      </div>
      <div className="sticky bottom-0 bg-background/95 backdrop-blur-md px-4 py-4">
        <div className="max-w-3xl mx-auto">
          {!hasMessages && (
            <div className="flex flex-wrap gap-2 mb-3">
              {suggestions.map((s, i) => (
                <button
                  key={i}
                  type="button"
                  onClick={() => sendMessage(s.query)}
                  disabled={loading}
                  className="inline-flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-full bg-muted/50 border border-border text-muted-foreground hover:text-primary hover:border-primary/30 hover:bg-primary/5 transition-all disabled:opacity-40"
                >
                  <s.icon className="h-3 w-3" />
                  {s.label}
                </button>
              ))}
            </div>
          )}

          {error && (
            <div className="mb-2.5 text-xs text-red-400 flex items-center gap-1.5 bg-red-400/5 border border-red-400/10 rounded-lg px-3 py-2">
              <AlertCircle className="h-3 w-3 flex-none" />
              {error}
            </div>
          )}

          <div className="bg-card rounded-2xl border border-border focus-within:border-primary/40 focus-within:shadow-[0_0_20px_hsl(var(--primary)_/_0.08)] transition-all duration-200 flex items-end gap-3 px-4 py-3 relative" ref={containerRef}>
            <button type="button" className="w-8 h-8 rounded-lg text-muted-foreground hover:text-primary hover:bg-muted/50 flex items-center justify-center transition-colors duration-200 flex-shrink-0 text-[11px] font-semibold tracking-wide" onClick={() => setShowGifPicker((v) => !v)}>GIF</button>
            {showGifPicker && <GifPicker onSelect={handleGifSelect} onClose={() => setShowGifPicker(false)} />}
            <textarea
              ref={textareaRef}
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onInput={handleTextareaInput}
              onKeyDown={handleKeyDown}
              placeholder="Ask for sales tips..."
              rows={1}
              className="bg-transparent flex-1 text-foreground text-sm placeholder-muted-foreground resize-none outline-none min-h-[24px] max-h-[200px] overflow-y-auto leading-6"
            />
            <button
              type="button"
              onClick={() => sendMessage()}
              disabled={!input.trim()}
              className={`w-9 h-9 rounded-xl flex-shrink-0 bg-gradient-to-br from-primary to-primary flex items-center justify-center text-white transition-all duration-200 ${input.trim() ? "hover:shadow-[0_0_20px_hsl(var(--primary)_/_0.4)] hover:scale-105 active:scale-95" : "opacity-40 cursor-not-allowed"}`}
            >
              <Send className="h-4 w-4" />
            </button>
          </div>
          <div className="flex justify-between items-center mt-2 px-1">
            <span className="text-muted-foreground text-[10px]">Shift + Enter for new line</span>
            <span className="text-muted-foreground text-[10px]">{input.length} / 2000</span>
          </div>
        </div>
      </div>
    </div>
  )
})

AIChat.displayName = "AIChat"
