'use client';
import { Collection, CollectionAccessType } from '@semble/types';
import {
Button,
Group,
Select,
Stack,
Textarea,
TextInput,
ThemeIcon,
} from '@mantine/core';
import { useForm } from '@mantine/form';
import useCreateCollection from '../../lib/mutations/useCreateCollection';
import { notifications } from '@mantine/notifications';
import { FaSeedling } from 'react-icons/fa6';
import { useQueryClient } from '@tanstack/react-query';
import { collectionKeys } from '../../lib/collectionKeys';
import { BsExclamation } from 'react-icons/bs';
interface Props {
onClose: () => void;
initialName?: string;
initialAccessType?: CollectionAccessType;
onCreate?: (collection: Collection) => void;
}
export default function CreateCollectionForm(props: Props) {
const createCollection = useCreateCollection();
const queryClient = useQueryClient();
const form = useForm({
initialValues: {
name: props.initialName ?? '',
description: '',
accessType: props.initialAccessType ?? CollectionAccessType.CLOSED,
},
});
const handleCreateCollection = (e: React.FormEvent) => {
e.preventDefault();
e.stopPropagation();
createCollection.mutate(
{
name: form.getValues().name,
description: form.getValues().description,
accessType: form.getValues().accessType,
},
{
onSuccess: async (data) => {
if (data?.collectionId && props.onCreate) {
// Wait for the query to refetch and get the new collection
await queryClient.refetchQueries({
queryKey: collectionKeys.mine(),
});
// Find the newly created collection from the cache
const queryState = queryClient.getQueryState<{
pages: Array<{ collections: Collection[] }>;
}>(collectionKeys.mine());
// Look through all pages to find the collection
const newCollection = queryState?.data?.pages
.flatMap((page) => page.collections ?? [])
.find((col) => col.id === data.collectionId);
if (newCollection) {
props.onCreate(newCollection);
}
}
props.onClose();
},
onError: () => {
notifications.show({
message: 'Could not create collection',
color: 'red',
title: 'Error',
position: 'top-center',
loading: false,
autoClose: false,
withCloseButton: true,
icon: