"use client";

import { useRef, useState } from "react";
import { cn } from "@/lib/utils";
import Swal from "sweetalert2";

// fnc_fileMultiUpload 대응
interface FileUploadProps {
  targetObjId: string;
  docType: string;
  docTypeName: string;
  onUploadComplete?: () => void;
  accept?: string;
  multiple?: boolean;
  className?: string;
  /** "button" (default) → 작은 첨부 버튼, "dropzone" → 점선 박스 큰 드롭 영역 */
  variant?: "button" | "dropzone";
  /** dropzone 모드일 때 높이(px). 기본 100 */
  dropzoneHeight?: number;
}

export function FileUpload({
  targetObjId,
  docType,
  docTypeName,
  onUploadComplete,
  accept,
  multiple = true,
  className,
  variant = "button",
  dropzoneHeight = 100,
}: FileUploadProps) {
  const inputRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);
  const [dragActive, setDragActive] = useState(false);

  const handleUpload = async (files: FileList | null) => {
    if (!files || files.length === 0) return;

    setUploading(true);
    try {
      for (let i = 0; i < files.length; i++) {
        const formData = new FormData();
        formData.append("file", files[i]);
        formData.append("targetObjId", targetObjId);
        formData.append("docType", docType);
        formData.append("docTypeName", docTypeName);

        const res = await fetch("/api/common/file-upload", {
          method: "POST",
          body: formData,
        });

        if (!res.ok) {
          throw new Error(`파일 업로드 실패: ${files[i].name}`);
        }
      }

      Swal.fire({
        icon: "success",
        title: "업로드 완료",
        text: `${files.length}개 파일이 업로드되었습니다.`,
        timer: 1500,
        showConfirmButton: false,
      });

      onUploadComplete?.();
    } catch (err) {
      Swal.fire({
        icon: "error",
        title: "업로드 실패",
        text: err instanceof Error ? err.message : "파일 업로드 중 오류가 발생했습니다.",
      });
    } finally {
      setUploading(false);
      if (inputRef.current) inputRef.current.value = "";
    }
  };

  const onDrop = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    setDragActive(false);
    if (uploading) return;
    handleUpload(e.dataTransfer.files);
  };

  if (variant === "dropzone") {
    return (
      <div className={cn("w-full", className)}>
        <input
          ref={inputRef}
          type="file"
          accept={accept}
          multiple={multiple}
          onChange={(e) => handleUpload(e.target.files)}
          className="hidden"
        />
        <div
          onClick={() => !uploading && inputRef.current?.click()}
          onDragOver={(e) => { e.preventDefault(); setDragActive(true); }}
          onDragLeave={() => setDragActive(false)}
          onDrop={onDrop}
          style={{ height: dropzoneHeight }}
          className={cn(
            "flex items-center justify-center w-full rounded border-2 border-dashed cursor-pointer transition-colors text-xs",
            dragActive ? "border-primary bg-primary/5 text-primary" : "border-blue-300 text-gray-400 hover:bg-gray-50",
            uploading && "cursor-not-allowed opacity-60",
          )}
        >
          {uploading ? "업로드중..." : "Drag & Drop Files Here"}
        </div>
      </div>
    );
  }

  return (
    <div className={cn("inline-flex items-center gap-2", className)}>
      <input
        ref={inputRef}
        type="file"
        accept={accept}
        multiple={multiple}
        onChange={(e) => handleUpload(e.target.files)}
        className="hidden"
      />
      <button
        type="button"
        onClick={() => inputRef.current?.click()}
        disabled={uploading}
        className="inline-flex items-center gap-1 rounded border border-gray-300 bg-white px-3 py-1.5 text-xs hover:bg-gray-50 disabled:opacity-50"
      >
        {uploading ? "업로드중..." : "파일첨부"}
      </button>
    </div>
  );
}
