'use client'

import { useState, useRef, useEffect, useCallback, Suspense } from 'react'
import { useSearchParams } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { Badge } from '@/components/ui/badge'
import { ScrollArea } from '@/components/ui/scroll-area'
import {
  Send,
  Bot,
  User,
  GraduationCap,
  Briefcase,
  Award,
  Building2,
  Sparkles,
  Loader2,
  AlertCircle,
  Trash2,
} from 'lucide-react'

/* ------------------------------------------------------------------ */
/* Types                                                               */
/* ------------------------------------------------------------------ */

interface Message {
  id: string
  role: 'user' | 'assistant'
  content: string
  timestamp: Date
}

/* ------------------------------------------------------------------ */
/* Simple markdown → HTML (no external lib)                            */
/* ------------------------------------------------------------------ */

function renderMarkdown(text: string): string {
  let html = text
  // Code blocks (```)
  html = html.replace(
    /```(\w*)\n?([\s\S]*?)```/g,
    '<pre class="bg-gray-100 rounded-md p-3 my-2 overflow-x-auto text-sm"><code>$2</code></pre>'
  )
  // Inline code
  html = html.replace(
    /`([^`]+)`/g,
    '<code class="bg-gray-100 px-1.5 py-0.5 rounded text-sm text-pink-600">$1</code>'
  )
  // Bold
  html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
  // Italic
  html = html.replace(/\*(.+?)\*/g, '<em>$1</em>')
  // Headings
  html = html.replace(/^### (.+)$/gm, '<h3 class="text-base font-semibold mt-3 mb-1">$1</h3>')
  html = html.replace(/^## (.+)$/gm, '<h2 class="text-lg font-semibold mt-4 mb-2">$1</h2>')
  html = html.replace(/^# (.+)$/gm, '<h1 class="text-xl font-bold mt-4 mb-2">$1</h1>')
  // Unordered lists
  html = html.replace(/^[*-] (.+)$/gm, '<li class="ml-4 list-disc">$1</li>')
  // Ordered lists
  html = html.replace(/^\d+\. (.+)$/gm, '<li class="ml-4 list-decimal">$1</li>')
  // Line breaks → paragraphs
  html = html.replace(/\n\n/g, '</p><p class="mt-2">')
  html = html.replace(/\n/g, '<br/>')
  html = `<p class="mt-1">${html}</p>`
  // Clean up empty paragraphs
  html = html.replace(/<p class="mt-[12]"><\/p>/g, '')
  return html
}

/* ------------------------------------------------------------------ */
/* Typing indicator                                                    */
/* ------------------------------------------------------------------ */

function TypingIndicator() {
  return (
    <div className="flex items-start gap-3 animate-in fade-in duration-300">
      <div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0" style={{ background: 'linear-gradient(135deg, #91C4D9 0%, #5b9ebd 100%)' }}>
        <Bot className="w-4 h-4 text-white" />
      </div>
      <div className="bg-white border rounded-2xl rounded-tl-sm px-4 py-3 max-w-[80%]">
        <div className="flex items-center gap-1.5">
          <span className="w-2 h-2 rounded-full bg-gray-400 animate-bounce" style={{ animationDelay: '0ms' }} />
          <span className="w-2 h-2 rounded-full bg-gray-400 animate-bounce" style={{ animationDelay: '150ms' }} />
          <span className="w-2 h-2 rounded-full bg-gray-400 animate-bounce" style={{ animationDelay: '300ms' }} />
        </div>
      </div>
    </div>
  )
}

/* ------------------------------------------------------------------ */
/* Quick‑action buttons                                                */
/* ------------------------------------------------------------------ */

const QUICK_ACTIONS = [
  { label: 'Career Advice', icon: Briefcase, prompt: 'I need help choosing a career path. What careers are in demand in South Africa?' },
  { label: 'Study Help', icon: GraduationCap, prompt: 'Can you give me some study tips for my exams? I am a South African student.' },
  { label: 'Bursary Info', icon: Award, prompt: 'What bursaries are available for South African students? How do I apply?' },
  { label: 'University Info', icon: Building2, prompt: 'What are the top universities in South Africa and their admission requirements?' },
] as const

/* ------------------------------------------------------------------ */
/* Inner component (needs searchParams, so must be inside Suspense)    */
/* ------------------------------------------------------------------ */

function AICoachInner() {
  const searchParams = useSearchParams()
  const [messages, setMessages] = useState<Message[]>([])
  const [input, setInput] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [modelStatus, setModelStatus] = useState<'loading' | 'online' | 'offline'>('loading')
  const [initialMsgSent, setInitialMsgSent] = useState(false)
  const messagesEndRef = useRef<HTMLDivElement>(null)
  const textareaRef = useRef<HTMLTextAreaElement>(null)

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

  useEffect(() => {
    scrollToBottom()
  }, [messages, isLoading, scrollToBottom])

  /* Check model health on mount */
  useEffect(() => {
    async function checkHealth() {
      try {
        const res = await fetch('/api/ai/chat', { method: 'OPTIONS' })
        setModelStatus(res.ok || res.status === 405 ? 'online' : 'offline')
      } catch {
        setModelStatus('offline')
      }
    }
    checkHealth()
  }, [])

  /* Handle initial message from query param (e.g., from Bursary/University pages) */
  useEffect(() => {
    const msg = searchParams.get('msg')
    if (msg && !initialMsgSent) {
      setInitialMsgSent(true)
      // Decode and send as initial message
      const decoded = decodeURIComponent(msg)
      const initialMsg: Message = {
        id: crypto.randomUUID(),
        role: 'user',
        content: decoded,
        timestamp: new Date(),
      }
      setMessages([initialMsg])
      setIsLoading(true)

      fetch('/api/ai/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          messages: [{ role: 'user', content: decoded }],
        }),
      })
        .then((res) => {
          if (!res.ok) throw new Error('Failed to get response')
          return res.json()
        })
        .then((data) => {
          const assistantMsg: Message = {
            id: crypto.randomUUID(),
            role: 'assistant',
            content: data.response,
            timestamp: new Date(),
          }
          setMessages((prev) => [...prev, assistantMsg])
          setModelStatus('online')
        })
        .catch(() => {
          setModelStatus('offline')
          const errorMsg: Message = {
            id: crypto.randomUUID(),
            role: 'assistant',
            content: "I'm sorry, I'm having trouble connecting right now. Please try again in a moment.",
            timestamp: new Date(),
          }
          setMessages((prev) => [...prev, errorMsg])
        })
        .finally(() => setIsLoading(false))
    }
  }, [searchParams, initialMsgSent])

  /* Send message */
  const sendMessage = async (content: string) => {
    if (!content.trim() || isLoading) return

    const userMsg: Message = {
      id: crypto.randomUUID(),
      role: 'user',
      content: content.trim(),
      timestamp: new Date(),
    }

    setMessages((prev) => [...prev, userMsg])
    setInput('')
    setIsLoading(true)
    setError(null)

    // Reset textarea height
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto'
    }

    try {
      const res = await fetch('/api/ai/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          messages: [...messages, userMsg].map((m) => ({
            role: m.role,
            content: m.content,
          })),
        }),
      })

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

      const data = await res.json()

      const assistantMsg: Message = {
        id: crypto.randomUUID(),
        role: 'assistant',
        content: data.response,
        timestamp: new Date(),
      }

      setMessages((prev) => [...prev, assistantMsg])
      setModelStatus('online')
    } catch (err) {
      const message = err instanceof Error ? err.message : 'An unexpected error occurred'
      setError(message)
      setModelStatus('offline')

      // Add error as assistant message
      const errorMsg: Message = {
        id: crypto.randomUUID(),
        role: 'assistant',
        content:
          "I'm sorry, I'm having trouble connecting right now. The AI model might be offline or still loading. Please try again in a moment. 🧠",
        timestamp: new Date(),
      }
      setMessages((prev) => [...prev, errorMsg])
    } finally {
      setIsLoading(false)
    }
  }

  /* Handle submit */
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    sendMessage(input)
  }

  /* Handle keyboard shortcut */
  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      sendMessage(input)
    }
  }

  /* Auto-resize textarea */
  const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setInput(e.target.value)
    const target = e.target
    target.style.height = 'auto'
    target.style.height = Math.min(target.scrollHeight, 150) + 'px'
  }

  /* Clear chat */
  const clearChat = () => {
    setMessages([])
    setError(null)
  }

  /* Format timestamp */
  const formatTime = (date: Date) => {
    return new Date(date).toLocaleTimeString('en-ZA', {
      hour: '2-digit',
      minute: '2-digit',
    })
  }

  return (
    <div className="flex flex-col h-[calc(100vh-3.5rem)] max-w-4xl mx-auto w-full">
      {/* Header */}
      <div className="flex items-center justify-between px-4 py-3 border-b bg-white">
        <div className="flex items-center gap-3">
          <div
            className="w-10 h-10 rounded-full flex items-center justify-center"
            style={{ background: 'linear-gradient(135deg, #91C4D9 0%, #5b9ebd 100%)' }}
          >
            <Sparkles className="w-5 h-5 text-white" />
          </div>
          <div>
            <h1 className="text-base font-semibold text-gray-900">AI Career Coach</h1>
            <div className="flex items-center gap-2">
              <span
                className={`w-2 h-2 rounded-full ${
                  modelStatus === 'online'
                    ? 'bg-green-500'
                    : modelStatus === 'loading'
                      ? 'bg-yellow-500 animate-pulse'
                      : 'bg-red-500'
                }`}
              />
              <span className="text-xs text-gray-500">
                {modelStatus === 'online'
                  ? 'Online'
                  : modelStatus === 'loading'
                    ? 'Checking...'
                    : 'Offline'}
              </span>
              <Badge variant="secondary" className="text-[10px] px-1.5 py-0">
                Granite 3.1 MoE
              </Badge>
            </div>
          </div>
        </div>
        {messages.length > 0 && (
          <Button
            variant="ghost"
            size="sm"
            onClick={clearChat}
            className="text-gray-500 hover:text-red-500"
          >
            <Trash2 className="w-4 h-4 mr-1" />
            Clear
          </Button>
        )}
      </div>

      {/* Messages */}
      <ScrollArea className="flex-1 px-4 py-4">
        <div className="space-y-4 max-w-none">
          {messages.length === 0 && !isLoading && (
            <div className="flex flex-col items-center justify-center py-16 text-center">
              <div
                className="w-20 h-20 rounded-2xl flex items-center justify-center mb-6"
                style={{ background: 'linear-gradient(135deg, #91C4D9 0%, #5b9ebd 100%)' }}
              >
                <Sparkles className="w-10 h-10 text-white" />
              </div>
              <h2 className="text-xl font-semibold text-gray-900 mb-2">
                Welcome to Studo-Guide AI Coach
              </h2>
              <p className="text-gray-500 max-w-md mb-8">
                I&apos;m your AI-powered career and education assistant, built specifically for
                South African students. Ask me about careers, bursaries, universities, study tips,
                and more!
              </p>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 w-full max-w-lg">
                {QUICK_ACTIONS.map((action) => (
                  <button
                    key={action.label}
                    onClick={() => sendMessage(action.prompt)}
                    className="flex items-center gap-3 p-3 bg-white border rounded-xl hover:shadow-md hover:border-[#91C4D9] transition-all text-left group"
                  >
                    <div
                      className="w-10 h-10 rounded-lg flex items-center justify-center shrink-0 transition-colors"
                      style={{ backgroundColor: '#f0f9ff' }}
                    >
                      <action.icon
                        className="w-5 h-5"
                        style={{ color: '#5b9ebd' }}
                      />
                    </div>
                    <span className="text-sm font-medium text-gray-700 group-hover:text-gray-900">
                      {action.label}
                    </span>
                  </button>
                ))}
              </div>
            </div>
          )}

          {messages.map((msg) => (
            <div
              key={msg.id}
              className={`flex items-start gap-3 animate-in fade-in slide-in-from-bottom-2 duration-300 ${
                msg.role === 'user' ? 'flex-row-reverse' : 'flex-row'
              }`}
            >
              {/* Avatar */}
              <div
                className={`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${
                  msg.role === 'user'
                    ? 'bg-[#91C4D9]'
                    : ''
                }`}
                style={
                  msg.role === 'assistant'
                    ? { background: 'linear-gradient(135deg, #91C4D9 0%, #5b9ebd 100%)' }
                    : undefined
                }
              >
                {msg.role === 'user' ? (
                  <User className="w-4 h-4 text-white" />
                ) : (
                  <Bot className="w-4 h-4 text-white" />
                )}
              </div>

              {/* Bubble */}
              <div
                className={`rounded-2xl px-4 py-3 max-w-[80%] ${
                  msg.role === 'user'
                    ? 'bg-[#91C4D9] text-white rounded-tr-sm'
                    : 'bg-white border rounded-tl-sm text-gray-800'
                }`}
              >
                <div
                  className={`text-sm leading-relaxed prose prose-sm max-w-none ${
                    msg.role === 'user' ? '' : 'prose-gray'
                  }`}
                  dangerouslySetInnerHTML={{
                    __html:
                      msg.role === 'assistant'
                        ? renderMarkdown(msg.content)
                        : msg.content.replace(/\n/g, '<br/>'),
                  }}
                />
                <div
                  className={`text-[10px] mt-1.5 ${
                    msg.role === 'user' ? 'text-white/70' : 'text-gray-400'
                  }`}
                >
                  {formatTime(msg.timestamp)}
                </div>
              </div>
            </div>
          ))}

          {isLoading && <TypingIndicator />}

          {error && !isLoading && (
            <div className="flex items-center gap-2 p-3 bg-red-50 border border-red-200 rounded-xl text-sm text-red-700 max-w-md mx-auto">
              <AlertCircle className="w-4 h-4 shrink-0" />
              <span>{error}</span>
            </div>
          )}

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

      {/* Quick actions bar (when chat is active) */}
      {messages.length > 0 && !isLoading && (
        <div className="px-4 py-2 border-t bg-white/80">
          <div className="flex items-center gap-2 overflow-x-auto pb-1">
            {QUICK_ACTIONS.map((action) => (
              <button
                key={action.label}
                onClick={() => sendMessage(action.prompt)}
                className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-gray-600 bg-gray-100 hover:bg-[#e8f4f8] hover:text-[#5b9ebd] rounded-full whitespace-nowrap transition-colors"
              >
                <action.icon className="w-3.5 h-3.5" />
                {action.label}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* Input area */}
      <div className="border-t bg-white p-4">
        <form onSubmit={handleSubmit} className="flex items-end gap-3">
          <div className="flex-1 relative">
            <Textarea
              ref={textareaRef}
              value={input}
              onChange={handleInputChange}
              onKeyDown={handleKeyDown}
              placeholder="Ask me about careers, bursaries, universities..."
              className="resize-none pr-4 min-h-[44px] max-h-[150px] rounded-xl border-gray-200 focus:border-[#91C4D9] focus:ring-[#91C4D9]/20"
              rows={1}
              disabled={isLoading}
            />
          </div>
          <Button
            type="submit"
            disabled={!input.trim() || isLoading}
            className="rounded-xl h-11 w-11 p-0 shrink-0"
            style={{ background: 'linear-gradient(135deg, #91C4D9 0%, #5b9ebd 100%)' }}
          >
            {isLoading ? (
              <Loader2 className="w-5 h-5 text-white animate-spin" />
            ) : (
              <Send className="w-5 h-5 text-white" />
            )}
          </Button>
        </form>
        <p className="text-[10px] text-gray-400 text-center mt-2">
          Powered by Granite 3.1 MoE &bull; AI responses may not always be accurate
        </p>
      </div>
    </div>
  )
}

/* ------------------------------------------------------------------ */
/* Main page — wraps inner in Suspense for useSearchParams()            */
/* ------------------------------------------------------------------ */

export default function AICoachPage() {
  return (
    <Suspense
      fallback={
        <div className="flex items-center justify-center h-[calc(100vh-3.5rem)]">
          <div className="animate-spin w-8 h-8 border-4 border-[#91C4D9] border-t-transparent rounded-full" />
        </div>
      }
    >
      <AICoachInner />
    </Suspense>
  )
}
