'use client'

import React, { useState, useEffect } from 'react'
import { useSDK } from '@/lib/sdk'

// =============================================================================
// TYPES
// =============================================================================

interface ChatMessage {
  id: string
  role: 'user' | 'assistant'
  content: string
  sources?: Source[]
  timestamp: Date
}

interface Source {
  title: string
  reference: string
  relevance: number
}

interface Regulation {
  name: string
  description?: string
  collection?: string
}

// =============================================================================
// COMPONENTS
// =============================================================================

function MessageBubble({ message }: { message: ChatMessage }) {
  const isUser = message.role === 'user'

  return (
    <div className={`flex ${isUser ? 'justify-end' : 'justify-start'}`}>
      <div className={`max-w-3xl ${isUser ? 'order-2' : 'order-1'}`}>
        <div
          className={`rounded-2xl px-4 py-3 ${
            isUser
              ? 'bg-purple-600 text-white'
              : 'bg-white border border-gray-200'
          }`}
        >
          <div className={`text-sm whitespace-pre-wrap ${isUser ? 'text-white' : 'text-gray-700'}`}>
            {message.content}
          </div>
        </div>

        {message.sources && message.sources.length > 0 && (
          <div className="mt-2 space-y-1">
            <p className="text-xs text-gray-500 ml-1">Quellen:</p>
            <div className="flex flex-wrap gap-2">
              {message.sources.map((source, i) => (
                <span
                  key={i}
                  className="inline-flex items-center gap-1 px-2 py-1 bg-blue-50 text-blue-700 text-xs rounded-lg hover:bg-blue-100 cursor-pointer"
                >
                  <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                  </svg>
                  {source.title}
                  {source.relevance > 0 && (
                    <span className="text-blue-400">({Math.round(source.relevance * 100)}%)</span>
                  )}
                </span>
              ))}
            </div>
          </div>
        )}

        <p className={`text-xs text-gray-400 mt-1 ${isUser ? 'text-right' : 'text-left'}`}>
          {message.timestamp.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' })}
        </p>
      </div>
    </div>
  )
}

// =============================================================================
// MAIN PAGE
// =============================================================================

const RAG_API = '/api/sdk/v1/rag'

const DEFAULT_QUESTIONS = [
  'Was sind die Rechte der Betroffenen nach DSGVO?',
  'Wie lange betraegt die Meldefrist bei einer Datenpanne?',
  'Welche Anforderungen stellt der AI Act an Hochrisiko-KI?',
  'Wann brauche ich einen Auftragsverarbeitungsvertrag?',
  'Was muss in einer Datenschutzerklaerung stehen?',
]

export default function RAGPage() {
  const { state } = useSDK()
  const [messages, setMessages] = useState<ChatMessage[]>([])
  const [inputValue, setInputValue] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [suggestedQuestions, setSuggestedQuestions] = useState<string[]>(DEFAULT_QUESTIONS)
  const [apiError, setApiError] = useState<string | null>(null)

  // Load regulations for suggested questions
  useEffect(() => {
    fetch(`${RAG_API}/regulations`)
      .then(res => res.ok ? res.json() : null)
      .then(data => {
        if (data && Array.isArray(data.regulations) && data.regulations.length > 0) {
          const regs: Regulation[] = data.regulations
          const dynamicQuestions = regs.slice(0, 5).map((r: Regulation) =>
            `Was sind die wichtigsten Anforderungen aus ${r.name}?`
          )
          setSuggestedQuestions(dynamicQuestions.length > 0 ? dynamicQuestions : DEFAULT_QUESTIONS)
        }
      })
      .catch(() => {
        // Keep default questions if API unavailable
      })
  }, [])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!inputValue.trim() || isLoading) return

    const userMessage: ChatMessage = {
      id: `msg-${Date.now()}`,
      role: 'user',
      content: inputValue,
      timestamp: new Date(),
    }

    setMessages(prev => [...prev, userMessage])
    setInputValue('')
    setIsLoading(true)
    setApiError(null)

    try {
      const res = await fetch(`${RAG_API}/search`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ query: inputValue, limit: 5 }),
      })

      if (!res.ok) {
        throw new Error(`HTTP ${res.status}`)
      }

      const data = await res.json()

      // Build assistant message from results
      const results = data.results || []
      let content = ''
      const sources: Source[] = []

      if (results.length === 0) {
        content = 'Zu dieser Frage wurden keine passenden Dokumente gefunden. Bitte formulieren Sie Ihre Frage anders oder waehlen Sie ein spezifischeres Thema.'
      } else {
        const snippets = results.map((r: any, i: number) => {
          const title = r.metadata?.title || r.metadata?.reference || `Dokument ${i + 1}`
          const ref = r.metadata?.reference || ''
          sources.push({ title, reference: ref, relevance: r.score || 0 })
          return `**${title}${ref ? ` (${ref})` : ''}**\n${r.content || ''}`
        })
        content = snippets.join('\n\n---\n\n')
      }

      const assistantMessage: ChatMessage = {
        id: `msg-${Date.now() + 1}`,
        role: 'assistant',
        content,
        sources,
        timestamp: new Date(),
      }
      setMessages(prev => [...prev, assistantMessage])
    } catch (err) {
      setApiError('RAG-Backend nicht erreichbar. Bitte pruefen Sie die Verbindung zum AI Compliance SDK.')
      // Remove the user message that didn't get a response
      setMessages(prev => prev.filter(m => m.id !== userMessage.id))
    } finally {
      setIsLoading(false)
    }
  }

  const handleSuggestedQuestion = (question: string) => {
    setInputValue(question)
  }

  return (
    <div className="flex flex-col h-[calc(100vh-200px)]">
      {/* Header */}
      <div className="flex-shrink-0 mb-6">
        <h1 className="text-2xl font-bold text-gray-900">Legal RAG</h1>
        <p className="mt-1 text-gray-500">
          Stellen Sie rechtliche Fragen zu DSGVO, AI Act und anderen Regelwerken
        </p>
      </div>

      {/* Info Box */}
      <div className="flex-shrink-0 bg-blue-50 border border-blue-200 rounded-xl p-4 mb-6">
        <div className="flex items-start gap-3">
          <svg className="w-5 h-5 text-blue-600 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          <div>
            <h4 className="font-medium text-blue-800">KI-gestuetzte Rechtsauskunft</h4>
            <p className="text-sm text-blue-600 mt-1">
              Das System durchsucht DSGVO, AI Act, BDSG und weitere Regelwerke, um Ihre Fragen zu beantworten.
              Die Antworten ersetzen keine Rechtsberatung.
            </p>
          </div>
        </div>
      </div>

      {/* Error Box */}
      {apiError && (
        <div className="flex-shrink-0 bg-red-50 border border-red-200 rounded-xl p-4 mb-4">
          <div className="flex items-center gap-3">
            <svg className="w-5 h-5 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
            </svg>
            <p className="text-sm text-red-700">{apiError}</p>
            <button onClick={() => setApiError(null)} className="ml-auto text-red-400 hover:text-red-600">
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
        </div>
      )}

      {/* Chat Area */}
      <div className="flex-1 overflow-y-auto bg-gray-50 rounded-xl border border-gray-200 p-6 space-y-6">
        {messages.length === 0 ? (
          <div className="text-center py-12">
            <div className="w-16 h-16 mx-auto bg-purple-100 rounded-full flex items-center justify-center mb-4">
              <svg className="w-8 h-8 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
              </svg>
            </div>
            <h3 className="text-lg font-semibold text-gray-900">Stellen Sie eine Frage</h3>
            <p className="mt-2 text-gray-500 max-w-md mx-auto">
              Fragen Sie zu DSGVO, AI Act, Datenschutz oder Compliance-Themen.
            </p>
          </div>
        ) : (
          messages.map(message => (
            <MessageBubble key={message.id} message={message} />
          ))
        )}

        {isLoading && (
          <div className="flex justify-start">
            <div className="bg-white border border-gray-200 rounded-2xl px-4 py-3">
              <div className="flex items-center gap-2">
                <div className="w-2 h-2 bg-purple-600 rounded-full animate-bounce" style={{ animationDelay: '0ms' }} />
                <div className="w-2 h-2 bg-purple-600 rounded-full animate-bounce" style={{ animationDelay: '150ms' }} />
                <div className="w-2 h-2 bg-purple-600 rounded-full animate-bounce" style={{ animationDelay: '300ms' }} />
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Suggested Questions */}
      {messages.length === 0 && (
        <div className="flex-shrink-0 mt-4">
          <p className="text-sm text-gray-500 mb-2">Vorgeschlagene Fragen:</p>
          <div className="flex flex-wrap gap-2">
            {suggestedQuestions.map((question, i) => (
              <button
                key={i}
                onClick={() => handleSuggestedQuestion(question)}
                className="px-3 py-2 text-sm bg-white border border-gray-200 rounded-lg hover:border-purple-300 hover:bg-purple-50 transition-colors"
              >
                {question}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* Input Area */}
      <form onSubmit={handleSubmit} className="flex-shrink-0 mt-4">
        <div className="flex items-end gap-4">
          <div className="flex-1 relative">
            <textarea
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                  e.preventDefault()
                  handleSubmit(e)
                }
              }}
              placeholder="Stellen Sie eine rechtliche Frage..."
              rows={2}
              className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-transparent resize-none"
            />
          </div>
          <button
            type="submit"
            disabled={!inputValue.trim() || isLoading}
            className={`px-6 py-3 rounded-xl font-medium transition-colors ${
              inputValue.trim() && !isLoading
                ? 'bg-purple-600 text-white hover:bg-purple-700'
                : 'bg-gray-200 text-gray-400 cursor-not-allowed'
            }`}
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
            </svg>
          </button>
        </div>
        <p className="text-xs text-gray-400 mt-2">
          Enter zum Senden, Shift+Enter fuer neue Zeile
        </p>
      </form>
    </div>
  )
}
