import { useState, useCallback } from "react";
import { chatApi } from "../api/chat";
import type { ChatFile } from "@paperclipai/shared";

export interface PendingFile {
  id: string;          // temp client-side id before upload completes
  file: File;          // raw File object
  name: string;
  mimeType: string;
  sizeBytes: number;
  progress: number;    // 0-100
  status: "uploading" | "done" | "error";
  uploadedFile?: ChatFile;  // set when upload completes
  contentPath?: string;
  error?: string;
}

export function useChatFileUpload(conversationId: string | null) {
  const [pendingFiles, setPendingFiles] = useState<PendingFile[]>([]);

  const addFile = useCallback(async (file: File) => {
    if (!conversationId) return;

    const tempId = crypto.randomUUID();
    const pending: PendingFile = {
      id: tempId,
      file,
      name: file.name,
      mimeType: file.type || "application/octet-stream",
      sizeBytes: file.size,
      progress: 0,
      status: "uploading",
    };

    setPendingFiles((prev) => [...prev, pending]);

    try {
      const result = await chatApi.uploadFile(
        conversationId,
        file,
        { source: "user_upload" },
        (percent) => {
          setPendingFiles((prev) =>
            prev.map((p) => (p.id === tempId ? { ...p, progress: percent } : p))
          );
        },
      );

      setPendingFiles((prev) =>
        prev.map((p) =>
          p.id === tempId
            ? { ...p, status: "done", progress: 100, uploadedFile: result.file, contentPath: result.contentPath }
            : p
        )
      );
    } catch (err) {
      setPendingFiles((prev) =>
        prev.map((p) =>
          p.id === tempId ? { ...p, status: "error", error: (err as Error).message } : p
        )
      );
    }
  }, [conversationId]);

  const removeFile = useCallback((tempId: string) => {
    setPendingFiles((prev) => prev.filter((p) => p.id !== tempId));
  }, []);

  const clearCompleted = useCallback(() => {
    setPendingFiles((prev) => prev.filter((p) => p.status !== "done"));
  }, []);

  const completedFileIds = pendingFiles
    .filter((p) => p.status === "done" && p.uploadedFile)
    .map((p) => p.uploadedFile!.id);

  return { pendingFiles, addFile, removeFile, clearCompleted, completedFileIds };
}
