import { PromotionModel } from "@insite/client-framework/Types/ApiModels";
import groupBy from "lodash/groupBy";
import { useEffect, useState } from "react";

const usePromotionCodeForm = (promotions?: PromotionModel[]) => {
    const [promotionCode, setPromotionCode] = useState("");
    const [promotionsWithCode, setPromotionsWithCode] = useState<PromotionModel[]>([]);
    const [removingPromotionCode, setRemovingPromotionCode] = useState("");
    const [isAddingDiscount, setIsAddingDiscount] = useState(false);
    const [isUpdatingPromotions, setIsUpdatingPromotions] = useState(false);

    useEffect(() => {
        if (promotions && promotions.length > 0) {
            const allPromotionsWithCode = promotions
                .map(o => ({ ...o, id: o.id.split(":")[0] })) // promo id may also contains orderline id
                .filter(o => o.promotionCode?.trim());
            const uniquePromotionsWithCode = Object.values(groupBy(allPromotionsWithCode, "id")).map(o => o[0]);
            setPromotionsWithCode(uniquePromotionsWithCode);
        } else {
            setPromotionsWithCode([]);
        }
    }, [promotions]);

    return {
        promotionCode,
        setPromotionCode,
        promotionsWithCode,
        setPromotionsWithCode,
        removingPromotionCode,
        setRemovingPromotionCode,
        isAddingDiscount,
        setIsAddingDiscount,
        isUpdatingPromotions,
        setIsUpdatingPromotions,
    };
};

export default usePromotionCodeForm;
