"use client";

import React, { useState } from "react";
import { Button } from "../ui/Button";
import { Input } from "../ui/Input";
import { Card, CardContent, CardHeader } from "../ui/Card";

// 답변에서 링크를 버튼으로 렌더링하는 함수
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;
  });
}

export interface RAGAnswerGeneratorProps {
  apiEndpoint?: string;
  placeholder?: string;
  maxResults?: number;
}

export function RAGAnswerGenerator({
  apiEndpoint = "/api/rag/answer/stream",
  placeholder = "질문을 입력하세요... (예: 회사 소개, 제품 정보 등)",
  maxResults = 5,
}: RAGAnswerGeneratorProps) {
  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(apiEndpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ query, k: maxResults }),
      });

      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
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder={placeholder}
          className="flex-1 h-10 rounded-md border border-gray-300 bg-white px-3 py-2 text-sm placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          onKeyDown={(e) => e.key === "Enter" && handleSearch()}
        />
        <Button
          onClick={handleSearch}
          disabled={loading || !query.trim()}
          loading={loading}
        >
          {loading ? "답변 생성 중..." : "질문하기"}
        </Button>
      </div>

      {/* AI 답변 */}
      {answer && (
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <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>
          </CardHeader>
          <CardContent>
            <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
                  variant="ghost"
                  size="sm"
                  onClick={() => setShowDetails(!showDetails)}
                >
                  {showDetails ? "상세 정보 숨기기" : "검색된 청크 보기"}
                </Button>

                {showDetails && (
                  <div className="mt-4 space-y-3">
                    <h4 className="text-sm font-medium text-gray-700">
                      🔍 검색된 청크들:
                    </h4>
                    {searchResults.map((result, index) => (
                      <div
                        key={index}
                        className="p-3 bg-gray-50 rounded border-l-4 border-blue-200"
                      >
                        <div className="text-xs text-gray-600 mb-2">
                          점수: {result.score?.toFixed(3)} | 출처:{" "}
                          {result.document?.source}
                        </div>
                        <div className="text-sm text-gray-800">
                          {result.chunk?.content || result.content}
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* 로딩 상태 */}
      {loading && (
        <div className="text-center py-8">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-2"></div>
          <p className="text-gray-600">AI가 답변을 생성하고 있습니다...</p>
        </div>
      )}
    </div>
  );
}
