"use client";

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

interface DocumentUploaderProps {
  ragEngine?: RAGEngine;
  onDocumentUploaded?: (document: any) => void;
  onDocumentDeleted?: (documentId: string) => void;
}

export function DocumentUploader({
  ragEngine,
  onDocumentUploaded,
  onDocumentDeleted,
}: DocumentUploaderProps) {
  const [isUploading, setIsUploading] = useState(false);
  const [uploadResults, setUploadResults] = useState<any[]>([]);
  const [uploadErrors, setUploadErrors] = useState<string[]>([]);
  const [dragActive, setDragActive] = useState(false);

  const handleFileUpload = async (files: FileList | File[]) => {
    if (!files || files.length === 0) return;

    setIsUploading(true);
    setUploadResults([]);
    setUploadErrors([]);

    try {
      const formData = new FormData();
      Array.from(files).forEach((file) => {
        formData.append("files", file);
      });

      const response = await fetch("/api/rag/upload", {
        method: "POST",
        body: formData,
      });

      const data = await response.json();

      if (data.success) {
        setUploadResults(data.results || []);
        if (data.errors && data.errors.length > 0) {
          setUploadErrors(data.errors);
        }

        // Notify parent component
        if (onDocumentUploaded && data.results) {
          data.results.forEach((result: any) => {
            onDocumentUploaded(result);
          });
        }
      } else {
        setUploadErrors([data.error || "업로드 중 오류가 발생했습니다."]);
      }
    } catch (error) {
      console.error("업로드 실패:", error);
      setUploadErrors(["네트워크 오류가 발생했습니다."]);
    } finally {
      setIsUploading(false);
    }
  };

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      handleFileUpload(e.target.files);
    }
  };

  const handleDrag = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === "dragenter" || e.type === "dragover") {
      setDragActive(true);
    } else if (e.type === "dragleave") {
      setDragActive(false);
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);

    if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
      handleFileUpload(e.dataTransfer.files);
    }
  };

  return (
    <div className="space-y-6">
      <div className="bg-white p-6 rounded-lg shadow">
        <h3 className="text-xl font-bold mb-4">문서 업로더</h3>
        <p className="text-gray-600 mb-4">
          PDF, Word, 텍스트 파일을 업로드하여 RAG 시스템에 추가할 수 있습니다.
        </p>

        <div
          className={`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${
            dragActive
              ? "border-blue-500 bg-blue-50"
              : "border-gray-300 hover:border-gray-400"
          }`}
          onDragEnter={handleDrag}
          onDragLeave={handleDrag}
          onDragOver={handleDrag}
          onDrop={handleDrop}
        >
          {isUploading ? (
            <div className="text-center">
              <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-500">파일 업로드 중...</p>
            </div>
          ) : (
            <>
              <p className="text-gray-500 mb-4">
                파일을 드래그하여 놓거나 클릭하여 선택하세요
              </p>
              <input
                type="file"
                multiple
                accept=".pdf,.doc,.docx,.txt,.md"
                className="hidden"
                id="file-upload"
                onChange={handleFileSelect}
                disabled={isUploading}
              />
              <label
                htmlFor="file-upload"
                className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 cursor-pointer disabled:opacity-50"
              >
                파일 선택
              </label>
              <p className="text-xs text-gray-500 mt-2">
                지원 형식: PDF, DOC, DOCX, TXT, MD (최대 10MB)
              </p>
            </>
          )}
        </div>
      </div>

      {/* 업로드 결과 */}
      {uploadResults.length > 0 && (
        <div className="bg-white p-6 rounded-lg shadow">
          <h4 className="text-lg font-semibold mb-4 text-green-600">
            ✅ 업로드 완료 ({uploadResults.length}개 파일)
          </h4>
          <div className="space-y-2">
            {uploadResults.map((result, index) => (
              <div
                key={index}
                className="flex justify-between items-center p-3 bg-green-50 rounded"
              >
                <div>
                  <p className="font-medium">{result.fileName}</p>
                  <p className="text-sm text-gray-600">
                    크기: {(result.fileSize / 1024).toFixed(1)}KB | ID:{" "}
                    {result.documentId}
                  </p>
                </div>
                <span className="text-green-600 font-semibold">
                  {result.status}
                </span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 업로드 에러 */}
      {uploadErrors.length > 0 && (
        <div className="bg-white p-6 rounded-lg shadow">
          <h4 className="text-lg font-semibold mb-4 text-red-600">
            ❌ 업로드 오류
          </h4>
          <div className="space-y-2">
            {uploadErrors.map((error, index) => (
              <div key={index} className="p-3 bg-red-50 rounded">
                <p className="text-red-700">{error}</p>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
