"use client";
import { API_URL } from '@/lib/api';

interface Props {
  entityType: string;
  entityId: number;
  onUploaded: () => void;
}

export default function DocumentUploader({
  entityType,
  entityId,
  onUploaded,
}: Props) {
  async function upload(
    files: FileList | null
  ) {
    if (!files) return;

    const formData = new FormData();

    formData.append(
      "entityType",
      entityType
    );

    formData.append(
      "entityId",
      entityId.toString()
    );

    for (let i = 0; i < files.length; i++) {
      formData.append(
        "files",
        files[i]
      );
    }

    try {
      await fetch(
        `${API_URL}/api/documents/upload`,
        {
          method: "POST",
          body: formData,
        }
      );

      onUploaded();
    } catch (error) {
      console.error(
        "Upload failed:",
        error
      );
    }
  }

  return (
    <label
      className="
        group
        flex
        min-h-[320px]
        cursor-pointer
        flex-col
        items-center
        justify-center
        rounded-2xl
        border-2
        border-dashed
        border-slate-300
        bg-slate-50
        px-8
        py-12
        text-center
        transition-all
        duration-200
        hover:border-[#1296E8]
        hover:bg-blue-50
      "
    >
      <div className="space-y-5">
        <div
          className="
            mx-auto
            flex
            h-20
            w-20
            items-center
            justify-center
            rounded-full
            bg-blue-100
            text-4xl
            transition-transform
            duration-200
            group-hover:scale-110
          "
        >
          📎
        </div>

        <div>
          <h3 className="text-3xl font-bold text-slate-800">
            Drop files here
          </h3>

          <p className="mt-3 text-lg text-slate-500">
            or click to browse
          </p>
        </div>

        <p className="mx-auto max-w-md text-sm leading-7 text-slate-400">
          PDF, Word, Excel, Images,
          Videos, ZIP, STL and DICOM
          files supported
        </p>
      </div>

      <input
        type="file"
        multiple
        className="hidden"
        onChange={(e) =>
          upload(e.target.files)
        }
      />
    </label>
  );
}
