import { AlertItem } from "../Shared/Alert";
import { BlankState } from "./BlanksReducer";


const validateBlanks = (
    blanks: BlankState[],
    answers: Map<string, string>,
    alerts: AlertItem[],
    setAlerts: React.Dispatch<React.SetStateAction<AlertItem[]>>,
    save: boolean = false,
): boolean => {
    const unfilledBlanks = blanks.filter(blank => !answers.has(blank.id.toString()));
    const filteredAlerts = alerts.filter(alert => alert.tag !== "unfilled-blanks");

    if (unfilledBlanks.length > 0) {
        if (!save && !filteredAlerts.some(alert => alert.tag === "editing")) {
            filteredAlerts.push({
                variant: "info",
                description: "You have unsaved changes. Don't forget to save your work!",
                tag: "editing"
            });
        }
        setAlerts([
            ...filteredAlerts,
            {
                variant: "error",
                tag: "unfilled-blanks",
                description: `${unfilledBlanks.length} blank${unfilledBlanks.length > 1 ? 's' : ''} ${unfilledBlanks.length > 1 ? 'are' : 'is'} missing a word (blanks: ${unfilledBlanks.map(blank => blank.id).join(", ")})`
            }
        ]);
        return false;
    } else if (filteredAlerts.length !== alerts.length) {
        setAlerts(filteredAlerts);
    }
    return true;
};

export default validateBlanks;
