"use client";

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

interface DocumentMetadata {
  title?: string;
  category?: string;
  tags?: string[];
  description?: string;
  version?: string;
}

interface UploadedDocument {
  id: string;
  name: string;
  size: number;
  uploadedAt: string;
  metadata: DocumentMetadata;
  path: string;
  url?: string;
}

interface DocumentUploaderClientProps {
  onDocumentUploaded?: (document: UploadedDocument) => void;
  onDocumentDeleted?: (documentId: string) => void;
  apiEndpoint?: string;
}

// Client-only DocumentUploader that uses API calls instead of RAGEngine
export function DocumentUploaderClient({
  onDocumentUploaded,
  onDocumentDeleted,
  apiEndpoint = "/api/rag",
}: DocumentUploaderClientProps) {
  const [documents, setDocuments] = useState<UploadedDocument[]>([]);
  const [isUploading, setIsUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  const loadDocuments = useCallback(async () => {
    try {
      const response = await fetch(`${apiEndpoint}/documents`);
      if (!response.ok) throw new Error("Failed to load documents");
      const docs = await response.json();
      setDocuments(docs);
    } catch (err) {
      setError("문서 목록을 불러오는데 실패했습니다.");
    }
  }, [apiEndpoint]);

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

  return (
    <div className="space-y-6">
      {error && (
        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md">
          {error}
        </div>
      )}

      {success && (
        <div className="bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-md">
          {success}
        </div>
      )}

      <div className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center">
        <div className="text-4xl">📄</div>
        <p className="text-lg font-medium text-gray-900 mt-4">
          API 기반 문서 업로드
        </p>
        <p className="text-sm text-gray-500 mt-2">
          서버 모듈을 클라이언트에서 분리하여 안전한 업로드를 제공합니다
        </p>
      </div>

      <div className="space-y-4">
        <h3 className="text-lg font-medium">
          업로드된 문서 ({documents.length})
        </h3>
        {documents.length === 0 ? (
          <p className="text-gray-500 text-center py-8">
            업로드된 문서가 없습니다.
          </p>
        ) : (
          documents.map((doc) => (
            <div key={doc.id} className="p-4 border rounded-lg">
              <h4 className="font-medium">{doc.name}</h4>
              <p className="text-sm text-gray-500">
                업로드: {new Date(doc.uploadedAt).toLocaleString()}
              </p>
            </div>
          ))
        )}
      </div>
    </div>
  );
}
