"use client"

import { useState, useRef, useEffect, Fragment } from "react"
import { Send, Bot, User, RefreshCw, AlertCircle, Check, Terminal } 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 [bootState, setBootState] = useState<"booting" | "ready" | "error">("booting")
  const messagesEndRef = useRef<HTMLDivElement>(null)

  const checkServer = 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(() => {
    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 = 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("/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()
    }
  }

  const bootOverlay = (
    <div className="flex-1 flex items-center justify-center">
      <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-4">
        <p className="text-sm text-[#6a6a75]">Servers booting...</p>
        <div className="h-[50px] w-[100px] bg-[#1a1a24] border border-[#2a2a35] rounded-lg 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="#1BB0CE" opacity="0.9"/>
              <rect x="6" y="6" width="6" height="2" rx="1" className="robot-arm-l" fill="#1BB0CE" opacity="0.7"/>
              <rect x="28" y="6" width="6" height="2" rx="1" className="robot-arm-r" fill="#1BB0CE" opacity="0.7"/>
              <rect x="14" y="5" width="4" height="4" rx="1" fill="#0d1117"/>
              <rect x="22" y="5" width="4" height="4" rx="1" fill="#0d1117"/>
              <circle cx="16" cy="7" r="1.5" className="robot-eye" fill="#1BB0CE"/>
              <circle cx="24" cy="7" r="1.5" className="robot-eye" fill="#1BB0CE"/>
              <rect x="17" y="10" width="6" height="2" rx="1" fill="#0d1117"/>
              <rect x="12" y="18" width="5" height="10" rx="2" className="robot-leg-l" fill="#1BB0CE" opacity="0.8"/>
              <rect x="23" y="18" width="5" height="10" rx="2" className="robot-leg-r" fill="#1BB0CE" opacity="0.8"/>
            </svg>
          </div>
        </div>
      </div>
    </div>
  )

  const readyOverlay = (
    <div className="flex-1 flex items-center justify-center">
      <div className="flex flex-col items-center gap-4">
        <div className="h-[50px] w-[100px] bg-[#1a1a24] border border-[#2a2a35] rounded-lg flex items-center justify-center">
          <Check className="h-6 w-6 text-green-400" />
        </div>
        <div className="text-center space-y-1">
          <p className="text-xs text-[#6a6a75]">Try these commands:</p>
          <div className="flex gap-2">
            <code className="text-xs px-2 py-1 rounded bg-[#2a2a35] text-[#1BB0CE] flex items-center gap-1"><Terminal className="h-3 w-3" /> lists</code>
            <code className="text-xs px-2 py-1 rounded bg-[#2a2a35] text-[#1BB0CE] flex items-center gap-1"><Terminal className="h-3 w-3" /> leads</code>
          </div>
        </div>
      </div>
    </div>
  )

  if (bootState === "booting") return bootOverlay

  return (
    <div className="flex flex-col h-full">
      {bootState === "ready" && readyOverlay}

      <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]">
              <svg className="h-4 w-4 animate-spin text-[#1BB0CE]" viewBox="0 0 24 24" fill="none">
                <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" opacity="0.25"/>
                <path d="M12 2a10 10 0 0 1 10 10" stroke="currentColor" strokeWidth="4" strokeLinecap="round"/>
              </svg>
            </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 ? (
              <svg className="h-4 w-4 animate-spin" viewBox="0 0 24 24" fill="none">
                <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" opacity="0.25"/>
                <path d="M12 2a10 10 0 0 1 10 10" stroke="currentColor" strokeWidth="4" strokeLinecap="round"/>
              </svg>
            ) : <Send className="h-4 w-4" />}
          </button>
        </div>
      </div>
    </div>
  )
}