"use client";

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

interface UploadResult {
  filename: string;
  success: boolean;
  chunks?: number;
  id?: string;
  error?: string;
}

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

export function DocumentUploader({
  ragEngine,
  onDocumentUploaded,
  onDocumentDeleted,
}: DocumentUploaderProps = {}) {
  const [dragActive, setDragActive] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [uploadResults, setUploadResults] = useState<UploadResult[]>([]);

  const handleFileUpload = async (files: FileList | File[]) => {
    setUploading(true);
    setUploadResults([]);

    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 result = await response.json();
      if (result.success) {
        setUploadResults(result.results || []);
        onDocumentUploaded?.();
      } else {
        setUploadResults([
          {
            filename: "업로드 실패",
            success: false,
            error: result.error || "알 수 없는 오류",
          },
        ]);
      }
    } catch (error) {
      console.error("파일 업로드 오류:", error);
      setUploadResults([
        {
          filename: "네트워크 오류",
          success: false,
          error: "서버와 연결할 수 없습니다.",
        },
      ]);
    } finally {
      setUploading(false);
    }
  };

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (files && files.length > 0) {
      handleFileUpload(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);

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

  return (
    <Card>
      <CardHeader>
        <h3 className="text-lg font-semibold">📁 문서 업로드</h3>
        <p className="text-sm text-gray-600">
          PDF, TXT, DOCX 파일을 업로드하여 RAG 시스템에 추가할 수 있습니다.
        </p>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* 드래그 앤 드롭 영역 */}
        <div
          className={`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${
            dragActive
              ? "border-blue-500 bg-blue-50"
              : "border-gray-300 bg-gray-50"
          }`}
          onDragEnter={handleDrag}
          onDragLeave={handleDrag}
          onDragOver={handleDrag}
          onDrop={handleDrop}
        >
          <div className="flex flex-col items-center space-y-2">
            <svg
              className="w-12 h-12 text-gray-400"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
              />
            </svg>
            <div className="space-y-1">
              <p className="text-lg font-medium text-gray-700">
                파일을 여기에 드래그하거나 클릭하여 업로드
              </p>
              <p className="text-sm text-gray-500">
                PDF, TXT, DOCX 파일 지원 (최대 10MB)
              </p>
            </div>
            <label className="cursor-pointer">
              <input
                type="file"
                multiple
                accept=".pdf,.txt,.docx"
                onChange={handleFileSelect}
                className="hidden"
                disabled={uploading}
              />
              <Button
                type="button"
                variant="outline"
                disabled={uploading}
                className="mt-2"
              >
                {uploading ? "업로드 중..." : "파일 선택"}
              </Button>
            </label>
          </div>
        </div>

        {/* 업로드 결과 */}
        {uploadResults.length > 0 && (
          <div className="space-y-2">
            <h4 className="font-medium text-gray-700">업로드 결과:</h4>
            <div className="space-y-2">
              {uploadResults.map((result, index) => (
                <div
                  key={index}
                  className={`p-3 rounded-md border ${
                    result.success
                      ? "bg-green-50 border-green-200"
                      : "bg-red-50 border-red-200"
                  }`}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-2">
                      <span
                        className={`text-sm ${
                          result.success ? "text-green-700" : "text-red-700"
                        }`}
                      >
                        {result.success ? "✅" : "❌"}
                      </span>
                      <span className="font-medium text-sm">
                        {result.filename}
                      </span>
                    </div>
                    {result.success && result.chunks && (
                      <span className="text-xs text-gray-600">
                        {result.chunks}개 청크 생성
                      </span>
                    )}
                  </div>
                  {result.error && (
                    <p className="text-xs text-red-600 mt-1">{result.error}</p>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
