import { useCallback, useEffect, useRef, useState } from 'react';
import type { TransferHandle, TransferOptions, TransferProgress } from '@shade/sdk';
import { useShadeRuntime } from './ShadeRuntimeProvider.js';

export interface UploadEntry {
  handle: TransferHandle;
  progress: TransferProgress | null;
  error: unknown;
  done: boolean;
}

export interface UseShadeUploadResult {
  /** Start a new upload. Resolves once the handle is available. */
  upload: (opts: TransferOptions) => Promise<TransferHandle>;
  /** Currently-tracked uploads (most recent first). */
  uploads: UploadEntry[];
  /** Drop a finished/failed entry from the list. */
  dismiss: (streamId: string) => void;
}

/**
 * Headless hook for upload tracking. Subscribes to progress events on each
 * started transfer and surfaces them as React state. Drop a custom UI on
 * top, or use the bundled `<ShadeUploader />` component.
 */
export function useShadeUpload(): UseShadeUploadResult {
  const shade = useShadeRuntime();
  const [uploads, setUploads] = useState<UploadEntry[]>([]);
  const mountedRef = useRef(true);

  useEffect(() => {
    mountedRef.current = true;
    return () => {
      mountedRef.current = false;
    };
  }, []);

  const upload = useCallback(
    async (opts: TransferOptions) => {
      const handle = await shade.upload(opts);
      const entry: UploadEntry = { handle, progress: null, error: null, done: false };
      setUploads((prev) => [entry, ...prev]);

      void (async () => {
        try {
          for await (const ev of handle.events) {
            if (!mountedRef.current) return;
            if (ev.type === 'progress') {
              setUploads((prev) =>
                prev.map((u) =>
                  u.handle.streamId === handle.streamId ? { ...u, progress: ev.progress } : u,
                ),
              );
            } else if (ev.type === 'complete') {
              setUploads((prev) =>
                prev.map((u) =>
                  u.handle.streamId === handle.streamId ? { ...u, done: true } : u,
                ),
              );
            } else if (ev.type === 'error') {
              setUploads((prev) =>
                prev.map((u) =>
                  u.handle.streamId === handle.streamId
                    ? { ...u, error: ev.error, done: true }
                    : u,
                ),
              );
            }
          }
        } catch (err) {
          if (!mountedRef.current) return;
          setUploads((prev) =>
            prev.map((u) =>
              u.handle.streamId === handle.streamId ? { ...u, error: err, done: true } : u,
            ),
          );
        }
      })();

      return handle;
    },
    [shade],
  );

  const dismiss = useCallback((streamId: string) => {
    setUploads((prev) => prev.filter((u) => u.handle.streamId !== streamId));
  }, []);

  return { upload, uploads, dismiss };
}
