"use client"

import { useState, useRef, useEffect, Fragment, forwardRef, useImperativeHandle, useCallback } from "react"
import { Bot, 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 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
  }
}

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


export interface AIChatHandle {
  fillInput: (text: string) => void
  addAssistantMessage: (content: string) => void
}

export const AIChat = forwardRef<AIChatHandle, 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)
    },
    addAssistantMessage(content: string) {
      setMessages((prev) => {
        if (!prev.some((m) => m.role === "user")) {
          return [
            { role: "user", content: "Search Facebook" },
            { role: "assistant", content },
          ]
        }
        return [...prev, { role: "assistant", content }]
      })
    },
  }), [])

  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/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ message: "ping" }),
      })
      if (res.status !== 503) {
        setBootState("ready")
      } else {
        setTimeout(checkServer, 2000)
      }
    } catch {
      setTimeout(checkServer, 2000)
    }
  }, [])

  useEffect(() => {
    checkServer()
    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])

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

  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">
        <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>
    )
  }

  if (bootState === "ready" && !hasUserMessage) {
    return (
      <div className="flex-1 flex flex-col overflow-y-auto" style={{ backgroundImage: "radial-gradient(circle, hsl(var(--border)) 1px, transparent 1px)", backgroundSize: "24px 24px" }}>
        <div className="flex-1 flex items-center justify-center">
          <div className="max-w-lg mx-auto px-4">
            <div className="float-in">
              <div className="w-16 h-16 rounded-2xl mx-auto mb-6 bg-gradient-to-br from-primary to-primary flex items-center justify-center shadow-[0_0_40px_hsl(var(--primary)_/_0.3)]">
                <Bot className="h-8 w-8 text-white" />
              </div>
              <h2 className="text-foreground font-bold text-2xl text-center mb-2">What can I help you with?</h2>
               <p className="text-muted-foreground text-sm text-center leading-relaxed">Your AI sales assistant is ready. Choose a quick action or type your question below.</p>
            </div>
          </div>
        </div>
        <div className="sticky bottom-0 bg-background/95 backdrop-blur-md px-4 py-4">
          <div className="max-w-3xl mx-auto">
            <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"}`}
              >
                ➤
              </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>
    )
  }

  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)}</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">
                <span className="w-2 h-2 rounded-full bg-primary dot-1" />
                <span className="w-2 h-2 rounded-full bg-primary dot-2" />
                <span className="w-2 h-2 rounded-full bg-primary dot-3" />
              </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">
          {error && (
            <div className="mb-2.5 text-xs text-red-400 flex items-center gap-1.5">
              <span>⚠️</span>
              {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"}`}
            >
              ➤
            </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"
