import useAccountStore from "@/store/account";
import useCollectionStore from "@/store/collections";
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
import Link from "next/link";
import { useRouter } from "next/router";
import React, { useEffect, useState } from "react";
import {
DragDropContext,
Draggable,
DraggableProvided,
} from "react-beautiful-dnd";
import { StrictModeDroppable as Droppable } from "./StrictModeDroppable";
type Props = {
links: boolean;
};
const CollectionSelection = ({ links }: Props) => {
const { collections } = useCollectionStore();
const { account, updateAccount } = useAccountStore();
// Use local state to store the collection order so we don't have to wait for a response from the API to update the UI
const [localCollectionOrder, setLocalCollectionOrder] = useState<
number[] | []
>([]);
const [active, setActive] = useState("");
const router = useRouter();
useEffect(() => {
setActive(router.asPath);
setLocalCollectionOrder(account.collectionOrder || []);
if (!account.collectionOrder || account.collectionOrder.length === 0) {
updateAccount({
...account,
collectionOrder: collections
.filter((e) => e.parentId === null) // Filter out collections with non-null parentId
.map((e) => e.id as number), // Use "as number" to assert that e.id is a number
});
}
}, [router, collections, account]);
return (
{
if (!result.destination) {
return; // Dragged outside the droppable area, do nothing
}
const updatedCollectionOrder = [...account.collectionOrder];
const [movedCollectionId] = updatedCollectionOrder.splice(
result.source.index,
1
);
updatedCollectionOrder.splice(
result.destination.index,
0,
movedCollectionId
);
// Update local state with the new collection order
setLocalCollectionOrder(updatedCollectionOrder);
// Update account with the new collection order
updateAccount({
...account,
collectionOrder: updatedCollectionOrder,
});
}}
>
{(provided) => (