"use client";

import React, { useState, useEffect } from "react";

export function ChunkManager() {
  const [chunks, setChunks] = useState<any[]>([]);
  const [stats, setStats] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const loadChunks = async () => {
    try {
      setLoading(true);
      setError(null);

      const response = await fetch("/api/rag/chunks");
      const data = await response.json();

      if (data.success) {
        setChunks(data.chunks || []);
        setStats(data.stats);
      } else {
        setError(data.error || "청크 정보를 불러오는데 실패했습니다.");
      }
    } catch (err) {
      console.error("청크 로딩 실패:", err);
      setError("청크 정보를 불러오는데 실패했습니다.");
    } finally {
      setLoading(false);
    }
  };

  const clearAllChunks = async () => {
    if (
      !confirm("모든 청크를 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.")
    ) {
      return;
    }

    try {
      setLoading(true);
      const response = await fetch("/api/rag/chunks", { method: "DELETE" });
      const data = await response.json();

      if (data.success) {
        alert("모든 청크가 성공적으로 삭제되었습니다.");
        setChunks([]);
        setStats(null);
      } else {
        setError(data.error || "청크 삭제에 실패했습니다.");
      }
    } catch (err) {
      console.error("청크 삭제 실패:", err);
      setError("청크 삭제에 실패했습니다.");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadChunks();
  }, []);

  return (
    <div className="space-y-4">
      {error && (
        <div className="p-4 bg-red-50 border border-red-200 text-red-800 rounded-md">
          {error}
        </div>
      )}

      {stats && (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div className="p-4 bg-blue-50 rounded-md">
            <div className="text-2xl font-bold">{stats.chunkCount}</div>
            <div className="text-sm text-gray-600">총 청크 수</div>
          </div>
          <div className="p-4 bg-green-50 rounded-md">
            <div className="text-2xl font-bold">{stats.documentCount}</div>
            <div className="text-sm text-gray-600">문서 수</div>
          </div>
          <div className="p-4 bg-purple-50 rounded-md">
            <div className="text-sm font-medium">{stats.embeddingModel}</div>
            <div className="text-xs text-gray-600">임베딩 모델</div>
          </div>
          <div className="p-4 bg-yellow-50 rounded-md">
            <div className="text-sm font-medium">{stats.vectorStoreType}</div>
            <div className="text-xs text-gray-600">벡터 스토어</div>
          </div>
        </div>
      )}

      <div className="flex justify-between items-center">
        <h3 className="text-lg font-semibold">청크 관리</h3>
        <div className="space-x-2">
          <button
            onClick={loadChunks}
            disabled={loading}
            className="px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700 disabled:opacity-50"
          >
            새로고침
          </button>
          <button
            onClick={clearAllChunks}
            disabled={loading || chunks.length === 0}
            className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 disabled:opacity-50"
          >
            모든 청크 삭제
          </button>
        </div>
      </div>

      {loading ? (
        <div className="text-center py-8">로딩 중...</div>
      ) : chunks.length === 0 ? (
        <div className="text-center py-8 text-gray-500">
          저장된 청크가 없습니다.
        </div>
      ) : (
        <div className="space-y-3">
          {chunks.map((chunk, index) => (
            <div
              key={chunk.id || index}
              className="p-4 border border-gray-200 rounded-md"
            >
              <div className="flex justify-between items-start mb-2">
                <div>
                  <h4 className="font-medium">
                    {chunk.documentTitle || "제목 없음"}
                  </h4>
                  <div className="text-sm text-gray-600">
                    {chunk.documentSource} • 청크 #{chunk.chunkIndex} •{" "}
                    {chunk.tokens} 토큰
                  </div>
                </div>
              </div>
              <div className="bg-gray-50 p-3 rounded text-sm">
                {chunk.content}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
