"use client"

import { useState, useRef, useEffect, Fragment } from "react"
import { Send, Loader2, Bot, User, RefreshCw, AlertCircle } from "lucide-react"

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-[#1BB0CE] hover:text-[#1BB0CE]/80">{part}</a>
    }
    return <Fragment key={i}>{part}</Fragment>
  })
}

interface ChatMessage {
  role: "user" | "assistant"
  content: string
}

export function AIChat() {
  const [messages, setMessages] = useState<ChatMessage[]>([])
  const [input, setInput] = useState("")
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState("")
  const [ollamaStatus, setOllamaStatus] = useState<boolean | null>(null)
  const messagesEndRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    fetch(`${AI_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.",
          },
        ])
      })
  }, [])



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

  const AI_API = process.env.NEXT_PUBLIC_AI_URL || "http://127.0.0.1:3001"

  const checkOllama = async () => {
    try {
      const res = await fetch(`${AI_API}/health`)
      const data = await res.json()
      setOllamaStatus(data.status === "ok")
    } catch {
      setOllamaStatus(false)
    }
  }

  useEffect(() => { checkOllama() }, [])

  const sendMessage = async () => {
    const msg = input.trim()
    if (!msg || loading) return

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

    try {
      const res = await fetch(`${AI_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)
    }
  }

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

  return (
    <div className="flex flex-col h-full">
      {ollamaStatus === false && (
        <div className="flex items-center gap-2 px-4 py-2 bg-amber-500/10 border-b border-amber-500/20 text-amber-400 text-xs">
          <AlertCircle className="h-3.5 w-3.5 flex-none" />
          <span className="flex-1">Ollama not responding. Start it with <code className="bg-amber-500/20 px-1 rounded">ollama serve</code></span>
          <button type="button" onClick={checkOllama} className="hover:text-amber-300">
            <RefreshCw className="h-3.5 w-3.5" />
          </button>
        </div>
      )}

      <div className="flex-1 overflow-y-auto p-4 space-y-4 scrollbar-thin">
        {messages.map((msg, i) => (
          <div key={i} className={`flex gap-3 ${msg.role === "user" ? "justify-end" : "justify-start"}`}>
            {msg.role === "assistant" && (
              <div className="h-8 w-8 rounded-full bg-[#1BB0CE]/20 flex items-center justify-center flex-none">
                <Bot className="h-4 w-4 text-[#1BB0CE]" />
              </div>
            )}
            <div
              className={`max-w-[75%] rounded-lg px-4 py-2.5 text-sm leading-relaxed whitespace-pre-wrap ${
                msg.role === "user"
                  ? "bg-[#1BB0CE] text-white"
                  : "bg-[#1a1a24] text-[#c8c8d0] border border-[#2a2a35]"
              }`}
            >
              {linkifyText(msg.content)}
            </div>
            {msg.role === "user" && (
              <div className="h-8 w-8 rounded-full bg-[#1BB0CE] flex items-center justify-center flex-none">
                <User className="h-4 w-4 text-white" />
              </div>
            )}
          </div>
        ))}
        {loading && (
          <div className="flex gap-3 justify-start">
            <div className="h-8 w-8 rounded-full bg-[#1BB0CE]/20 flex items-center justify-center flex-none">
              <Bot className="h-4 w-4 text-[#1BB0CE]" />
            </div>
            <div className="max-w-[75%] rounded-lg px-4 py-2.5 bg-[#1a1a24] border border-[#2a2a35]">
              <Loader2 className="h-4 w-4 animate-spin text-[#1BB0CE]" />
            </div>
          </div>
        )}
        <div ref={messagesEndRef} />
      </div>

      <div className="border-t border-[#2a2a35] p-4">
        {error && (
          <div className="mb-2 text-xs text-red-400 flex items-center gap-1.5">
            <AlertCircle className="h-3 w-3" />
            {error}
          </div>
        )}
        <div className="flex gap-2">
          <textarea
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="Ask for sales tips..."
            rows={1}
            className="flex-1 bg-[#1a1a24] border border-[#2a2a35] rounded-lg px-3 py-2 text-sm text-[#e8e8ef] placeholder-[#6a6a75] resize-none outline-none focus:border-[#1BB0CE]/50"
          />
          <button
            type="button"
            onClick={sendMessage}
            disabled={loading || !input.trim()}
            className="h-9 w-9 rounded-lg bg-[#1BB0CE] hover:bg-[#1BB0CE]/80 disabled:opacity-40 flex items-center justify-center flex-none transition-colors"
          >
            {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
          </button>
        </div>
      </div>
    </div>
  )
}
