"use client";

import { useState, useRef } from "react";
import {
  uploadMailFiles,
  getUploadProgress,
  type UploadJob,
} from "@/lib/api";

export function useAdminUpload() {
  const [uploadDragging, setUploadDragging] = useState(false);
  const [uploadJob, setUploadJob] = useState<UploadJob | null>(null);
  const [uploadError, setUploadError] = useState("");
  const [uploadLoading, setUploadLoading] = useState(false);
  const uploadPollRef = useRef<ReturnType<typeof setInterval> | null>(null);

  async function handleUploadFiles(files: File[]) {
    const valid = files.filter(f => f.name.toLowerCase().endsWith(".eml") || f.name.toLowerCase().endsWith(".mbox"));
    if (valid.length === 0) {
      setUploadError("Nur .eml und .mbox Dateien erlaubt.");
      return;
    }
    setUploadError("");
    setUploadJob(null);
    setUploadLoading(true);
    try {
      const { job_id } = await uploadMailFiles(valid);
      const poll = setInterval(async () => {
        try {
          const job = await getUploadProgress(job_id);
          setUploadJob(job);
          if (job.status !== "running") {
            clearInterval(poll);
            uploadPollRef.current = null;
            setUploadLoading(false);
          }
        } catch {
          clearInterval(poll);
          uploadPollRef.current = null;
          setUploadLoading(false);
        }
      }, 1500);
      uploadPollRef.current = poll;
    } catch (e: unknown) {
      setUploadError(e instanceof Error ? e.message : "Upload fehlgeschlagen.");
      setUploadLoading(false);
    }
  }

  return {
    uploadDragging,
    setUploadDragging,
    uploadJob,
    uploadError,
    uploadLoading,
    handleUploadFiles,
  };
}
