import React from "react";
import { LexoRank } from "lexorank";
import { useCrudOperations } from "@/hooks/cruds/baseCrud";
import {
    CreateDealSchema,
    DealSchema,
    StatusSchema,
    UpdateDealSchema,
} from "@/lib/client";
import {
    createDealMutation,
    deleteDealMutation,
    updateDealMutation,
} from "@/lib/client/@tanstack/react-query.gen";
import { getNewLexorank } from "@/utils/lexorank";

type UseDealsOperationsProps = {
    deals: DealSchema[];
    setDeals: React.Dispatch<React.SetStateAction<DealSchema[]>>;
    refetchDeals: () => void;
    boardId?: number;
    statuses: StatusSchema[];
};

export type DealsCrud = {
    onCreate: (name: string) => void;
    onUpdate: (dealId: number, deal: UpdateDealSchema) => void;
    onDelete: (deal: DealSchema, onSuccess?: () => void) => void;
};

export const useDealsCrud = ({
    deals,
    setDeals,
    refetchDeals,
    boardId,
    statuses,
}: UseDealsOperationsProps): DealsCrud => {
    return useCrudOperations<DealSchema, UpdateDealSchema, CreateDealSchema>({
        entities: deals,
        setEntities: setDeals,
        refetch: refetchDeals,
        mutations: {
            create: createDealMutation(),
            update: updateDealMutation(),
            delete: deleteDealMutation(),
        },
        getCreateEntity: name => {
            if (!boardId || statuses.length === 0) return null;
            const firstStatus = statuses[0];
            const filteredDeals = deals.filter(
                d => d.statusId === firstStatus.id
            );
            let firstDeal: DealSchema | null = null;
            if (filteredDeals.length > 0) {
                firstDeal = filteredDeals[0];
            }
            const newLexorank = getNewLexorank(
                null,
                firstDeal ? LexoRank.parse(firstDeal.lexorank) : null
            );
            return {
                name,
                boardId,
                statusId: firstStatus.id,
                lexorank: newLexorank.toString(),
            };
        },
        getUpdateEntity: (old, update) => ({
            ...old,
            name: update.name ?? old.name,
            lexorank: update.lexorank ?? old.lexorank,
            statusId: update.statusId ?? old.statusId,
        }),
        getDeleteConfirmTitle: () => "Удаление сделки",
    });
};
