"use client";

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

export function useMailUpload(onImportDone: () => void) {
  const [uploadOpen, setUploadOpen] = useState(false);
  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: FileList | File[]) {
    const allowed = Array.from(files).filter((f) => {
      const n = f.name.toLowerCase();
      return n.endsWith(".eml") || n.endsWith(".mbox");
    });
    if (allowed.length === 0) {
      setUploadError("Nur .eml und .mbox Dateien erlaubt.");
      return;
    }
    setUploadError("");
    setUploadJob(null);
    setUploadLoading(true);
    try {
      const { job_id } = await uploadMailFilesUser(allowed);
      uploadPollRef.current = setInterval(async () => {
        try {
          const job = await getUploadProgressUser(job_id);
          setUploadJob(job);
          if (job.status !== "running") {
            clearInterval(uploadPollRef.current!);
            uploadPollRef.current = null;
            setUploadLoading(false);
            // Refresh search results after successful import
            if (job.status === "done") onImportDone();
          }
        } catch {
          clearInterval(uploadPollRef.current!);
          uploadPollRef.current = null;
          setUploadLoading(false);
        }
      }, 1500);
    } catch (e) {
      setUploadError(e instanceof Error ? e.message : "Upload fehlgeschlagen.");
      setUploadLoading(false);
    }
  }

  function handleUploadClose() {
    if (uploadPollRef.current) {
      clearInterval(uploadPollRef.current);
      uploadPollRef.current = null;
    }
    setUploadOpen(false);
    setUploadJob(null);
    setUploadError("");
    setUploadLoading(false);
  }

  return {
    uploadOpen,
    setUploadOpen,
    uploadDragging,
    setUploadDragging,
    uploadJob,
    uploadError,
    uploadLoading,
    handleUploadFiles,
    handleUploadClose,
  };
}
