"use client";

import { useCallback, useRef, useState } from "react";
import { toast } from "sonner";

import { useAdminConfig } from "@/components/admin/admin-config";

import type { MediaItem } from "./types";
import { preflightImage, uploadImage } from "./upload-client";

export type UploadTask = {
  id: string;
  name: string;
  progress: number;
  status: "uploading" | "done" | "error";
  error?: string;
  media?: MediaItem;
};

/**
 * Uploads images with per-file progress. Failures show a toast and stay in
 * `tasks` with their error, so the UI can show what went wrong.
 */
export function useImageUpload() {
  const { maxUploadMb } = useAdminConfig();
  const [tasks, setTasks] = useState<UploadTask[]>([]);
  const controllers = useRef(new Map<string, AbortController>());

  const patch = (id: string, change: Partial<UploadTask>) =>
    setTasks((current) =>
      current.map((task) => (task.id === id ? { ...task, ...change } : task)),
    );

  const upload = useCallback(
    async (files: File[]): Promise<MediaItem[]> => {
      const uploaded: MediaItem[] = [];

      await Promise.all(
        files.map(async (file) => {
          const id = crypto.randomUUID();
          const problem = preflightImage(file, maxUploadMb);
          setTasks((current) => [
            ...current,
            {
              id,
              name: file.name,
              progress: 0,
              status: problem ? "error" : "uploading",
              error: problem ?? undefined,
            },
          ]);
          if (problem) {
            toast.error(problem);
            return;
          }

          const controller = new AbortController();
          controllers.current.set(id, controller);
          try {
            const media = await uploadImage(file, {
              signal: controller.signal,
              onProgress: (progress) => patch(id, { progress }),
            });
            patch(id, { status: "done", progress: 100, media });
            uploaded.push(media);
          } catch (error) {
            const message =
              error instanceof Error ? error.message : "Upload failed.";
            patch(id, { status: "error", error: message });
            toast.error(`${file.name}: ${message}`);
          } finally {
            controllers.current.delete(id);
          }
        }),
      );

      return uploaded;
    },
    [maxUploadMb],
  );

  const cancel = (id: string) => controllers.current.get(id)?.abort();
  const clearFinished = () =>
    setTasks((current) =>
      current.filter((task) => task.status === "uploading"),
    );

  return {
    upload,
    cancel,
    clearFinished,
    tasks,
    uploading: tasks.some((task) => task.status === "uploading"),
    maxUploadMb,
  };
}
