/**
 * Upload Hook
 */

import { useState, useCallback, useRef } from 'react';

interface UploadOptions {
  endpoint?: string;
  onProgress?: (progress: number) => void;
  headers?: Record<string, string>;
}

interface UploadResult {
  url: string;
  key: string;
}

interface UseUploadOptions {
  onSuccess?: (data: unknown) => void;
  onError?: (error: unknown) => void;
  onCancel?: () => void;
}

export const useUpload = (options?: UseUploadOptions) => {
  const [progress, setProgress] = useState(0);
  const [isUploading, setIsUploading] = useState(false);
  const abortControllerRef = useRef<AbortController | null>(null);

  const upload = useCallback(async (
    endpointOrFile: string | File,
    fileOrOptions?: File | UploadOptions,
    uploadOptions?: UploadOptions
  ): Promise<UploadResult | void> => {
    setIsUploading(true);
    setProgress(0);
    abortControllerRef.current = new AbortController();

    // Handle different call signatures
    let endpoint: string | undefined;
    let file: File;
    let optionsCombined: UploadOptions | undefined;

    if (typeof endpointOrFile === 'string') {
      // Signature: upload(url, file, options)
      endpoint = endpointOrFile;
      file = fileOrOptions as File;
      optionsCombined = uploadOptions;
    } else {
      // Signature: upload(file, options)
      file = endpointOrFile;
      optionsCombined = fileOrOptions as UploadOptions | undefined;
    }

    const formData = new FormData();
    formData.append('file', file);

    try {
      // Simulate upload progress
      setProgress(50);

      // In a real implementation, this would upload to the endpoint
      // For now, return a placeholder
      const result: UploadResult = {
        url: URL.createObjectURL(file),
        key: `uploads/${file.name}`,
      };

      setProgress(100);
      options?.onSuccess?.(result);
      return result;
    } catch (error) {
      if ((error as Error).name === 'AbortError') {
        options?.onCancel?.();
      } else {
        options?.onError?.(error);
      }
    } finally {
      setIsUploading(false);
    }
  }, [options]);

  const cancel = useCallback(() => {
    abortControllerRef.current?.abort();
    setIsUploading(false);
    setProgress(0);
  }, []);

  return {
    upload,
    progress,
    isUploading,
    cancel,
  };
};
