"use client";

import React, { useState, useEffect } from "react";
import { RAGEngine } from "../../../../rag";

// 답변에서 링크를 버튼으로 렌더링하는 함수
function renderAnswerWithLinks(text: string) {
  if (!text) return text;

  // 네이버 블로그 링크 패턴 감지
  const linkPattern = /(https?:\/\/blog\.naver\.com\/[^\s\n]+)/g;

  // 링크가 실제로 존재하는지 확인 (새로운 정규식 인스턴스 사용)
  if (!/(https?:\/\/blog\.naver\.com\/[^\s\n]+)/.test(text)) {
    return text; // 링크가 없으면 원본 텍스트 그대로 반환
  }

  const parts = text.split(linkPattern);

  return parts.map((part, index) => {
    if (part.match(linkPattern)) {
      return (
        <a
          key={index}
          href={part}
          target="_blank"
          rel="noopener noreferrer"
          className="inline-flex items-center gap-1 mx-1 px-3 py-1 bg-green-100 text-green-700 rounded-full text-sm hover:bg-green-200 transition-colors font-medium"
          title="원문 보기"
        >
          <svg
            className="w-3 h-3"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
            />
          </svg>
          🔗 원문 보기
        </a>
      );
    }
    return part;
  });
}

// RAG 답변 생성 컴포넌트
function RAGAnswerGenerator() {
  const [query, setQuery] = useState("");
  const [answer, setAnswer] = useState("");
  const [sources, setSources] = useState<any[]>([]);
  const [searchResults, setSearchResults] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [showDetails, setShowDetails] = useState(false);

  const handleSearch = async () => {
    if (!query.trim()) return;

    try {
      setLoading(true);
      setAnswer("");
      setSources([]);
      setSearchResults([]);

      const response = await fetch("/api/rag/answer/stream", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ query, k: 5 }),
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error("스트림을 읽을 수 없습니다.");
      }

      const decoder = new TextDecoder();
      let buffer = "";
      let currentAnswer = "";

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split("\n");
        buffer = lines.pop() || "";

        for (const line of lines) {
          if (line.trim()) {
            try {
              const data = JSON.parse(line);

              if (data.type === "sources") {
                setSources(data.content || []);
              } else if (data.type === "content") {
                currentAnswer += data.content;
                setAnswer(currentAnswer);
              } else if (data.type === "error") {
                setAnswer(`오류: ${data.content}`);
                break;
              }
            } catch (e) {
              // JSON 파싱 오류 무시
            }
          }
        }
      }
    } catch (error) {
      console.error("RAG 답변 생성 중 오류:", error);
      setAnswer("네트워크 오류가 발생했습니다.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      {/* 검색 입력 */}
      <div className="flex gap-2">
        <input
          type="text"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="질문을 입력하세요... (예: 회사 소개, 제품 정보 등)"
          className="flex-1 px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          onKeyPress={(e) => e.key === "Enter" && handleSearch()}
        />
        <button
          onClick={handleSearch}
          disabled={loading || !query.trim()}
          className="px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {loading ? "답변 생성 중..." : "질문하기"}
        </button>
      </div>

      {/* AI 답변 */}
      {answer && (
        <div className="bg-white border border-gray-200 rounded-lg p-6 shadow-sm">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-semibold text-gray-900">🤖 AI 답변</h3>
            {sources.length > 0 && (
              <span className="text-sm text-gray-500">
                {sources.length}개 문서 참조
              </span>
            )}
          </div>

          <div className="prose max-w-none">
            <div className="text-gray-800 leading-relaxed whitespace-pre-wrap">
              {renderAnswerWithLinks(answer)}
            </div>
          </div>

          {/* 참조 소스 - RSS가 아닌 문서만 표시 */}
          {sources.filter((source) => !source.isRSS).length > 0 && (
            <div className="mt-6 pt-4 border-t border-gray-200">
              <h4 className="text-sm font-medium text-gray-700 mb-3">
                📚 참조 문서:
              </h4>
              <div className="space-y-2">
                {sources
                  .filter((source) => !source.isRSS)
                  .map((source, index) => (
                    <div
                      key={index}
                      className="flex items-center gap-2 text-sm"
                    >
                      <span className="bg-blue-100 text-blue-800 px-2 py-1 rounded text-xs font-medium">
                        {source.index}
                      </span>
                      <div className="flex-1">
                        <span className="text-gray-700 truncate block max-w-md">
                          {source.title}
                        </span>
                      </div>
                      <span className="text-gray-500 text-xs">
                        {(source.score * 100).toFixed(0)}%
                      </span>
                    </div>
                  ))}
              </div>
            </div>
          )}

          {/* 상세 정보 토글 */}
          {searchResults.length > 0 && (
            <div className="mt-4">
              <button
                onClick={() => setShowDetails(!showDetails)}
                className="text-sm text-blue-600 hover:text-blue-800 underline"
              >
                {showDetails ? "상세 정보 숨기기" : "상세 정보 보기"}
              </button>

              {showDetails && (
                <div className="mt-4 space-y-3">
                  {searchResults.map((result, index) => (
                    <div
                      key={index}
                      className="bg-gray-50 p-4 rounded-lg border"
                    >
                      <div className="flex items-center justify-between mb-2">
                        <span className="text-sm font-medium text-gray-900">
                          문서 #{index + 1}
                        </span>
                        <span className="text-xs text-gray-500">
                          유사도: {(result.score * 100).toFixed(1)}%
                        </span>
                      </div>
                      <p className="text-sm text-gray-700 mb-2">
                        {result.content}
                      </p>
                      {result.metadata && (
                        <div className="text-xs text-gray-500">
                          메타데이터: {JSON.stringify(result.metadata)}
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

interface RAGManagerProps {
  ragEngine: RAGEngine;
  onRetrainTriggered?: () => void;
}

export function RAGManager({ ragEngine, onRetrainTriggered }: RAGManagerProps) {
  const [activeTab, setActiveTab] = useState("generator");

  const tabs = [
    { id: "generator", label: "AI 답변 생성", component: RAGAnswerGenerator },
  ];

  return (
    <div className="max-w-6xl mx-auto p-6 space-y-6">
      <div className="bg-white rounded-lg shadow-sm border border-gray-200">
        <div className="border-b border-gray-200">
          <nav className="flex space-x-8 px-6" aria-label="Tabs">
            {tabs.map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`py-4 px-1 border-b-2 font-medium text-sm ${
                  activeTab === tab.id
                    ? "border-blue-500 text-blue-600"
                    : "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
                }`}
              >
                {tab.label}
              </button>
            ))}
          </nav>
        </div>

        <div className="p-6">
          {tabs.map((tab) => {
            if (tab.id === activeTab) {
              const Component = tab.component;
              return <Component key={tab.id} />;
            }
            return null;
          })}
        </div>
      </div>
    </div>
  );
}
