import React from "react";
import { LexoRank } from "lexorank";
import { useCrudOperations } from "@/hooks/cruds/baseCrud";
import {
    CreateStatusSchema,
    StatusSchema,
    UpdateStatusSchema,
} from "@/lib/client";
import {
    createStatusMutation,
    deleteStatusMutation,
    updateStatusMutation,
} from "@/lib/client/@tanstack/react-query.gen";
import { getMaxByLexorank, getNewLexorank } from "@/utils/lexorank";

type Props = {
    statuses: StatusSchema[];
    setStatuses: React.Dispatch<React.SetStateAction<StatusSchema[]>>;
    refetchStatuses: () => void;
    boardId?: number;
};

export type StatusesCrud = {
    onCreate: (name: string) => void;
    onUpdate: (statusId: number, status: UpdateStatusSchema) => void;
    onDelete: (status: StatusSchema) => void;
};

export const useStatusesCrud = ({
    statuses,
    setStatuses,
    refetchStatuses,
    boardId,
}: Props): StatusesCrud => {
    return useCrudOperations<
        StatusSchema,
        UpdateStatusSchema,
        CreateStatusSchema
    >({
        entities: statuses,
        setEntities: setStatuses,
        refetch: refetchStatuses,
        mutations: {
            create: createStatusMutation(),
            update: updateStatusMutation(),
            delete: deleteStatusMutation(),
        },
        getCreateEntity: name => {
            if (!boardId) return null;
            const lastBoard = getMaxByLexorank(statuses);
            const newLexorank = getNewLexorank(
                lastBoard ? LexoRank.parse(lastBoard.lexorank) : null
            );
            return {
                name,
                boardId,
                lexorank: newLexorank.toString(),
            };
        },
        getUpdateEntity: (old, update) => ({
            ...old,
            name: update.name ?? old.name,
            lexorank: update.lexorank ?? old.lexorank,
        }),
        getDeleteConfirmTitle: () => "Удаление статуса",
    });
};
