/**
 * Knowledge Base Query Panel
 * Interactive chat interface for testing knowledge base queries
 */

"use client";

import { useState, useRef, useEffect } from "react";
import type { Lang } from "@/lib/config";
import { fetchWithCSRF } from "@/lib/csrf-client";
import type { KBMediaType } from "@/lib/types/knowledge-base.types";
import { MEDIA_TYPE_LABELS } from "@/lib/types/knowledge-base.types";
import {
  Send,
  Bot,
  User,
  Loader2,
  FileText,
  MessageSquare,
  Sparkles,
  Copy,
  Check,
  ThumbsUp,
  ThumbsDown,
  Trash2,
  ChevronDown,
  ChevronUp,
  Image as ImageIcon,
  Video,
  Music,
  Upload as UploadIcon,
} from "lucide-react";

interface KnowledgeBaseQueryPanelProps {
  lang: Lang;
}

interface MediaResult {
  type: KBMediaType;
  url: string;
  title: string;
  description?: string;
  relevanceScore: number;
  thumbnailUrl?: string;
}

interface Source {
  id: string;
  documentId: string;
  documentTitle: string;
  content: string;
  relevanceScore: number;
  mediaType?: KBMediaType;
  mediaUrl?: string;
}

interface FAQ {
  id: string;
  question: string;
  answer: string;
  category: string;
}

interface Message {
  id: string;
  role: "user" | "assistant";
  content: string;
  sources?: Source[];
  relatedFAQs?: FAQ[];
  mediaResults?: MediaResult[];
  timestamp: Date;
  metadata?: {
    model?: string;
    queryTimeMs?: number;
    ragEngine?: string;
  };
  feedback?: "positive" | "negative" | null;
}

const getSourceIcon = (mediaType?: string) => {
  switch (mediaType) {
    case "image":
      return ImageIcon;
    case "video":
      return Video;
    case "audio":
      return Music;
    default:
      return FileText;
  }
};

export default function KnowledgeBaseQueryPanel({
  lang,
}: KnowledgeBaseQueryPanelProps) {
  const isAr = lang === "ar";
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [copiedId, setCopiedId] = useState<string | null>(null);
  const [expandedSources, setExpandedSources] = useState<string | null>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLTextAreaElement>(null);

  // Scroll to bottom when messages change
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  // Auto-resize textarea
  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.style.height = "auto";
      inputRef.current.style.height = `${Math.min(inputRef.current.scrollHeight, 150)}px`;
    }
  }, [input]);

  // Send query
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!input.trim() || loading) return;

    const userMessage: Message = {
      id: `user-${Date.now()}`,
      role: "user",
      content: input.trim(),
      timestamp: new Date(),
    };

    setMessages((prev) => [...prev, userMessage]);
    setInput("");
    setLoading(true);

    try {
      const response = await fetchWithCSRF(
        "/api/dashboard/knowledge-base/query",
        {
          method: "POST",
          body: JSON.stringify({
            query: userMessage.content,
            language: lang,
            includeCitations: true,
            useGeminiRAG: false,
          }),
        },
      );

      const data = await response.json();

      const assistantMessage: Message = {
        id: `assistant-${Date.now()}`,
        role: "assistant",
        content: data.success
          ? data.answer ||
            (isAr
              ? "لم أتمكن من العثور على إجابة."
              : "I couldn't find an answer.")
          : data.error || (isAr ? "حدث خطأ" : "An error occurred"),
        sources: data.sources || [],
        relatedFAQs: data.relatedFAQs || [],
        mediaResults: data.mediaResults || [],
        timestamp: new Date(),
        metadata: data.aiMetadata,
      };

      setMessages((prev) => [...prev, assistantMessage]);
    } catch {
      const errorMessage: Message = {
        id: `error-${Date.now()}`,
        role: "assistant",
        content: isAr
          ? "حدث خطأ أثناء الاتصال. يرجى المحاولة مرة أخرى."
          : "A connection error occurred. Please try again.",
        timestamp: new Date(),
      };
      setMessages((prev) => [...prev, errorMessage]);
    } finally {
      setLoading(false);
    }
  };

  // Handle image-based similarity search
  const handleImageQuery = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const userMessage: Message = {
      id: `user-${Date.now()}`,
      role: "user",
      content: `[Image search: ${file.name}]`,
      timestamp: new Date(),
    };
    setMessages((prev) => [...prev, userMessage]);
    setLoading(true);

    try {
      const formData = new FormData();
      formData.append("image", file);
      formData.append("language", lang);

      const csrfToken = await fetch("/api/csrf")
        .then((r) => r.json())
        .then((d) => d.csrfToken);
      const response = await fetch("/api/dashboard/knowledge-base/query", {
        method: "POST",
        headers: { "x-csrf-token": csrfToken },
        body: formData,
      });
      const data = await response.json();

      const assistantMessage: Message = {
        id: `assistant-${Date.now()}`,
        role: "assistant",
        content:
          data.answer ||
          (isAr ? "لم أجد نتائج مشابهة." : "No similar results found."),
        sources: data.sources || [],
        mediaResults: data.mediaResults || [],
        timestamp: new Date(),
        metadata: data.aiMetadata,
      };
      setMessages((prev) => [...prev, assistantMessage]);
    } catch {
      setMessages((prev) => [
        ...prev,
        {
          id: `error-${Date.now()}`,
          role: "assistant" as const,
          content: isAr ? "حدث خطأ في البحث بالصورة" : "Image search failed",
          timestamp: new Date(),
        },
      ]);
    } finally {
      setLoading(false);
    }
  };

  // Copy message to clipboard
  const handleCopy = async (content: string, id: string) => {
    await navigator.clipboard.writeText(content);
    setCopiedId(id);
    setTimeout(() => setCopiedId(null), 2000);
  };

  // Provide feedback
  const handleFeedback = (
    messageId: string,
    feedback: "positive" | "negative",
  ) => {
    setMessages((prev) =>
      prev.map((msg) => (msg.id === messageId ? { ...msg, feedback } : msg)),
    );
    // TODO: Send feedback to API for improving responses
  };

  // Clear conversation
  const handleClear = () => {
    setMessages([]);
  };

  // Suggested questions
  const suggestedQuestions = isAr
    ? [
        "ما هي سياسة الإلغاء لديكم؟",
        "كيف يمكنني حجز موعد؟",
        "ما هي ساعات العمل؟",
        "ما هي طرق الدفع المتاحة؟",
      ]
    : [
        "What is your cancellation policy?",
        "How can I book an appointment?",
        "What are your working hours?",
        "What payment methods do you accept?",
      ];

  return (
    <div className="flex flex-col h-[600px] rounded-xl border border-slate-200 bg-white overflow-hidden">
      {/* Header */}
      <div className="flex items-center justify-between px-4 py-3 border-b border-slate-200 bg-gradient-to-r from-brand-green/5 to-emerald-50">
        <div className="flex items-center gap-3">
          <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-brand-green">
            <Sparkles className="h-5 w-5 text-white" />
          </div>
          <div>
            <h3 className="font-semibold text-slate-900">
              {isAr ? "اختبار قاعدة المعرفة" : "Test Knowledge Base"}
            </h3>
            <p className="text-xs text-slate-500">
              {isAr
                ? "اسأل أي سؤال لاختبار الذكاء الاصطناعي"
                : "Ask any question to test the AI"}
            </p>
          </div>
        </div>
        {messages.length > 0 && (
          <button
            onClick={handleClear}
            className="flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium text-slate-600 hover:bg-slate-100 transition-colors"
          >
            <Trash2 className="h-3.5 w-3.5" />
            {isAr ? "مسح" : "Clear"}
          </button>
        )}
      </div>

      {/* Messages */}
      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        {messages.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-full text-center">
            <div className="flex h-16 w-16 items-center justify-center rounded-full bg-gradient-to-br from-brand-green/10 to-emerald-100 mb-4">
              <Bot className="h-8 w-8 text-brand-green" />
            </div>
            <h4 className="text-lg font-semibold text-slate-900 mb-2">
              {isAr ? "ابدأ محادثة" : "Start a Conversation"}
            </h4>
            <p className="text-sm text-slate-500 max-w-sm mb-6">
              {isAr
                ? "اسأل أي سؤال لترى كيف سيرد الذكاء الاصطناعي بناءً على قاعدة معرفتك"
                : "Ask any question to see how the AI will respond based on your knowledge base"}
            </p>

            {/* Suggested Questions */}
            <div className="w-full max-w-md">
              <p className="text-xs font-medium text-slate-400 mb-2">
                {isAr ? "أسئلة مقترحة:" : "Suggested questions:"}
              </p>
              <div className="grid grid-cols-1 gap-2">
                {suggestedQuestions.map((question, idx) => (
                  <button
                    key={idx}
                    onClick={() => setInput(question)}
                    className="flex items-center gap-2 rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 hover:border-brand-green/30 transition-colors text-left"
                  >
                    <MessageSquare className="h-4 w-4 text-slate-400 flex-shrink-0" />
                    <span className="truncate">{question}</span>
                  </button>
                ))}
              </div>
            </div>
          </div>
        ) : (
          messages.map((message) => (
            <div
              key={message.id}
              className={`flex gap-3 ${
                message.role === "user" ? "justify-end" : "justify-start"
              }`}
            >
              {message.role === "assistant" && (
                <div className="flex h-8 w-8 items-center justify-center rounded-full bg-brand-green flex-shrink-0">
                  <Bot className="h-4 w-4 text-white" />
                </div>
              )}

              <div
                className={`max-w-[80%] ${
                  message.role === "user" ? "order-first" : ""
                }`}
              >
                <div
                  className={`rounded-2xl px-4 py-3 ${
                    message.role === "user"
                      ? "bg-brand-green text-white rounded-br-md"
                      : "bg-slate-100 text-slate-900 rounded-bl-md"
                  }`}
                >
                  <p className="text-sm whitespace-pre-wrap">
                    {message.content}
                  </p>
                </div>

                {/* Inline Media Results */}
                {message.role === "assistant" &&
                  message.mediaResults &&
                  message.mediaResults.length > 0 && (
                    <div className="mt-3 space-y-2">
                      <p className="text-xs font-medium text-slate-500">
                        {isAr ? "الوسائط ذات الصلة:" : "Related Media:"}
                      </p>
                      <div className="grid grid-cols-2 gap-2">
                        {message.mediaResults.map((media, idx) => (
                          <div
                            key={idx}
                            className="rounded-lg border border-slate-200 overflow-hidden bg-white"
                          >
                            {media.type === "image" && (
                              <img
                                src={media.url}
                                alt={media.title}
                                className="w-full h-32 object-cover"
                              />
                            )}
                            {media.type === "video" && (
                              <video
                                src={media.url}
                                controls
                                className="w-full h-32 object-cover"
                              />
                            )}
                            {media.type === "audio" && (
                              <div className="p-3 flex items-center gap-2">
                                <Music className="h-5 w-5 text-violet-500" />
                                <audio
                                  src={media.url}
                                  controls
                                  className="flex-1 h-8"
                                />
                              </div>
                            )}
                            <div className="p-2">
                              <p className="text-xs font-medium text-slate-700 truncate">
                                {media.title}
                              </p>
                              <div className="flex items-center justify-between mt-1">
                                <span className="text-xs text-slate-400">
                                  {MEDIA_TYPE_LABELS[media.type]?.[
                                    isAr ? "ar" : "en"
                                  ] || media.type}
                                </span>
                                <span className="text-xs font-medium text-emerald-600">
                                  {Math.round(media.relevanceScore * 100)}%
                                </span>
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                {/* Sources & FAQs */}
                {message.role === "assistant" &&
                (message.sources?.length || message.relatedFAQs?.length) ? (
                  <div className="mt-2">
                    <button
                      onClick={() =>
                        setExpandedSources(
                          expandedSources === message.id ? null : message.id,
                        )
                      }
                      className="flex items-center gap-1 text-xs text-slate-500 hover:text-slate-700"
                    >
                      {expandedSources === message.id ? (
                        <ChevronUp className="h-3 w-3" />
                      ) : (
                        <ChevronDown className="h-3 w-3" />
                      )}
                      {message.sources?.length || 0}{" "}
                      {isAr ? "مصادر" : "sources"}
                      {message.relatedFAQs?.length
                        ? ` • ${message.relatedFAQs.length} ${isAr ? "أسئلة ذات صلة" : "related FAQs"}`
                        : ""}
                    </button>

                    {expandedSources === message.id && (
                      <div className="mt-2 space-y-2">
                        {message.sources?.map((source, idx) => {
                          const SourceIcon = getSourceIcon(source.mediaType);
                          return (
                            <div
                              key={idx}
                              className="rounded-lg border border-slate-200 bg-white p-3"
                            >
                              <div className="flex items-center gap-2 text-xs font-medium text-slate-700 mb-1">
                                <SourceIcon className="h-3 w-3" />
                                {source.documentTitle}
                              </div>
                              <p className="text-xs text-slate-500 line-clamp-2">
                                {source.content}
                              </p>
                            </div>
                          );
                        })}

                        {message.relatedFAQs?.map((faq, idx) => (
                          <div
                            key={idx}
                            className="rounded-lg border border-violet-200 bg-violet-50 p-3"
                          >
                            <p className="text-xs font-medium text-violet-800">
                              {faq.question}
                            </p>
                            <p className="text-xs text-violet-600 mt-1 line-clamp-2">
                              {faq.answer}
                            </p>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                ) : null}

                {/* Actions */}
                {message.role === "assistant" && (
                  <div className="flex items-center gap-2 mt-2">
                    <button
                      onClick={() => handleCopy(message.content, message.id)}
                      className="flex items-center gap-1 rounded px-2 py-1 text-xs text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition-colors"
                    >
                      {copiedId === message.id ? (
                        <Check className="h-3 w-3 text-emerald-500" />
                      ) : (
                        <Copy className="h-3 w-3" />
                      )}
                      {copiedId === message.id
                        ? isAr
                          ? "تم النسخ"
                          : "Copied"
                        : isAr
                          ? "نسخ"
                          : "Copy"}
                    </button>

                    <div className="flex items-center border-l border-slate-200 pl-2 gap-1">
                      <button
                        onClick={() => handleFeedback(message.id, "positive")}
                        className={`rounded p-1 transition-colors ${
                          message.feedback === "positive"
                            ? "text-emerald-500 bg-emerald-50"
                            : "text-slate-400 hover:text-emerald-500 hover:bg-emerald-50"
                        }`}
                      >
                        <ThumbsUp className="h-3 w-3" />
                      </button>
                      <button
                        onClick={() => handleFeedback(message.id, "negative")}
                        className={`rounded p-1 transition-colors ${
                          message.feedback === "negative"
                            ? "text-red-500 bg-red-50"
                            : "text-slate-400 hover:text-red-500 hover:bg-red-50"
                        }`}
                      >
                        <ThumbsDown className="h-3 w-3" />
                      </button>
                    </div>

                    {message.metadata?.ragEngine && (
                      <span className="text-xs text-slate-400 ml-auto">
                        {message.metadata.ragEngine === "pinecone-multimodal"
                          ? "Pinecone RAG"
                          : message.metadata.ragEngine === "gemini-file-search"
                            ? "Gemini RAG"
                            : "Keyword Search"}
                        {message.metadata.queryTimeMs
                          ? ` • ${message.metadata.queryTimeMs}ms`
                          : ""}
                      </span>
                    )}
                  </div>
                )}

                {/* Timestamp */}
                <p className="text-xs text-slate-400 mt-1">
                  {message.timestamp.toLocaleTimeString(
                    isAr ? "ar-QA" : "en-US",
                    {
                      hour: "2-digit",
                      minute: "2-digit",
                    },
                  )}
                </p>
              </div>

              {message.role === "user" && (
                <div className="flex h-8 w-8 items-center justify-center rounded-full bg-slate-200 flex-shrink-0">
                  <User className="h-4 w-4 text-slate-600" />
                </div>
              )}
            </div>
          ))
        )}

        {/* Loading indicator */}
        {loading && (
          <div className="flex gap-3">
            <div className="flex h-8 w-8 items-center justify-center rounded-full bg-brand-green flex-shrink-0">
              <Bot className="h-4 w-4 text-white" />
            </div>
            <div className="bg-slate-100 rounded-2xl rounded-bl-md px-4 py-3">
              <div className="flex items-center gap-2">
                <Loader2 className="h-4 w-4 animate-spin text-brand-green" />
                <span className="text-sm text-slate-500">
                  {isAr ? "جاري البحث..." : "Searching..."}
                </span>
              </div>
            </div>
          </div>
        )}

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

      {/* Input */}
      <form
        onSubmit={handleSubmit}
        className="p-4 border-t border-slate-200 bg-slate-50"
      >
        <div className="flex items-end gap-2">
          <label
            className="flex h-8 w-8 items-center justify-center rounded-lg text-slate-400 hover:text-brand-green hover:bg-brand-green/10 transition-colors cursor-pointer"
            title={isAr ? "بحث بالصورة" : "Search by image"}
          >
            <UploadIcon className="h-4 w-4" />
            <input
              type="file"
              accept="image/*"
              className="hidden"
              onChange={handleImageQuery}
            />
          </label>
          <div className="flex-1 relative">
            <textarea
              ref={inputRef}
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter" && !e.shiftKey) {
                  e.preventDefault();
                  handleSubmit(e);
                }
              }}
              placeholder={
                isAr ? "اكتب سؤالك هنا..." : "Type your question here..."
              }
              disabled={loading}
              rows={1}
              className="w-full resize-none rounded-xl border border-slate-200 bg-white px-4 py-3 pr-12 text-sm placeholder-slate-400 focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 focus:outline-none disabled:opacity-50"
              style={{ minHeight: "48px", maxHeight: "150px" }}
            />
            <button
              type="submit"
              disabled={!input.trim() || loading}
              className="absolute bottom-2 right-2 flex h-8 w-8 items-center justify-center rounded-lg bg-brand-green text-white hover:bg-brand-greenHover transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {loading ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Send className="h-4 w-4" />
              )}
            </button>
          </div>
        </div>
        <p className="mt-2 text-xs text-slate-400 text-center">
          {isAr
            ? "اضغط Enter للإرسال • Shift+Enter لسطر جديد"
            : "Press Enter to send • Shift+Enter for new line"}
        </p>
      </form>
    </div>
  );
}
