import {
  createContext,
  type FC,
  type PropsWithChildren,
  useContext,
  useState,
} from 'react';

type FormFileUploadContextType = {
  uploadingFiles: Record<string, boolean>;
  setUploadingFiles: React.Dispatch<
    React.SetStateAction<Record<string, boolean>>
  >;
  isUploadingAny: boolean;
  isUploadingByFieldName: (fieldName: string) => boolean;
};

const FormFileUploadContext = createContext<
  FormFileUploadContextType | undefined
>(undefined);

export const FormFileUploadProvider: FC<PropsWithChildren> = ({ children }) => {
  const [uploadingFiles, setUploadingFiles] = useState<Record<string, boolean>>(
    {},
  );

  const isUploadingAny = Object.values(uploadingFiles).some(
    isUploading => isUploading,
  );

  const isUploadingByFieldName = (fieldName: string) =>
    uploadingFiles[fieldName];

  return (
    <FormFileUploadContext.Provider
      value={{
        uploadingFiles,
        setUploadingFiles,
        isUploadingAny,
        isUploadingByFieldName,
      }}
    >
      {children}
    </FormFileUploadContext.Provider>
  );
};

export const useFormFileUpload = () => {
  const context = useContext(FormFileUploadContext);
  if (!context) {
    throw new Error(
      'useFormFileUpload must be used within a FormFileUploadProvider',
    );
  }
  return context;
};
