import { LexoRank } from "lexorank";
import { useStatusesContext } from "@/app/deals/contexts/StatusesContext";
import { DealSchema } from "@/client";
import { getNewLexorank, sortByLexorank } from "@/utils/lexorank";

const useGetNewRank = () => {
    const { statuses } = useStatusesContext();

    const getNewRankForSameStatus = (
        statusDeals: DealSchema[],
        overDealIndex: number,
        activeDealId: number
    ) => {
        const activeDealIndex = statusDeals.findIndex(
            deal => deal.id === activeDealId
        );
        const [leftIndex, rightIndex] =
            overDealIndex < activeDealIndex
                ? [overDealIndex - 1, overDealIndex]
                : [overDealIndex, overDealIndex + 1];

        const leftLexorank =
            leftIndex >= 0
                ? LexoRank.parse(statusDeals[leftIndex].lexorank)
                : null;
        const rightLexorank =
            rightIndex < statusDeals.length
                ? LexoRank.parse(statusDeals[rightIndex].lexorank)
                : null;

        return getNewLexorank(leftLexorank, rightLexorank).toString();
    };

    const getNewRankForAnotherStatus = (
        statusDeals: DealSchema[],
        overDealIndex: number
    ) => {
        const leftLexorank =
            overDealIndex > 0
                ? LexoRank.parse(statusDeals[overDealIndex - 1].lexorank)
                : null;
        const rightLexorank = LexoRank.parse(
            statusDeals[overDealIndex].lexorank
        );

        return getNewLexorank(leftLexorank, rightLexorank).toString();
    };

    const getNewStatusRank = (activeStatusId: number, overStatusId: number) => {
        const sortedStatusList = sortByLexorank(statuses);
        const overIndex = sortedStatusList.findIndex(
            s => s.id === overStatusId
        );
        const activeIndex = sortedStatusList.findIndex(
            s => s.id === activeStatusId
        );

        if (overIndex === -1 || activeIndex === -1) return null;

        const [leftIndex, rightIndex] =
            overIndex < activeIndex
                ? [overIndex - 1, overIndex]
                : [overIndex, overIndex + 1];

        const leftLexorank =
            leftIndex >= 0
                ? LexoRank.parse(statuses[leftIndex].lexorank)
                : null;
        const rightLexorank =
            rightIndex < statuses.length
                ? LexoRank.parse(statuses[rightIndex].lexorank)
                : null;

        return getNewLexorank(leftLexorank, rightLexorank).toString();
    };

    return {
        getNewRankForSameStatus,
        getNewRankForAnotherStatus,
        getNewStatusRank,
    };
};

export default useGetNewRank;
