import { AlertItem } from "../Shared/Alert";
import { ParsedQuestion, reconstructLine } from "./parsing";


const validatePlaceholders = (text: string, originalId: string): { isValid: boolean; message?: string } => {
    const matches = text.match(/\[(\d+)\]/g) || [];
    
    if (matches.length === 0) {
        return { 
            isValid: false, 
            message: "Each question must have exactly one blank" 
        };
    }
    
    if (matches.length > 1) {
        return { 
            isValid: false, 
            message: "Only one blank is allowed per question" 
        };
    }
    
    const idMatch = matches[0]?.match(/\[(\d+)\]/);
    if (!idMatch || idMatch[1] !== originalId) {
        return { 
            isValid: false, 
            message: "The blank ID cannot be changed" 
        };
    }

    return { isValid: true };
};

const validateQuestions = (
    parsedQuestions: ParsedQuestion[],
    setAlerts: React.Dispatch<React.SetStateAction<AlertItem[]>>
): boolean => {
    const emptyQuestions = parsedQuestions.filter(q => reconstructLine(q.parts).trim() === '');
    if (emptyQuestions.length > 0) {
        setAlerts(prev => {
            const filteredAlerts = prev.filter(alert => !alert.tag?.startsWith('empty-question'));
            return [...filteredAlerts, ...emptyQuestions.map(q => ({
                variant: "error" as const,
                tag: `empty-question-${q.id}`,
                description: `Question ${q.id} is empty`
            }))];
        });
        return false;
    }
    setAlerts(prev => prev.filter(alert => !alert.tag?.startsWith('empty-question')));
    return true;
};

const validateEmptySolutions = (
    solutions: Array<{ id: string; solution: string[] }>,
    setAlerts: React.Dispatch<React.SetStateAction<AlertItem[]>>
): boolean => {
    const questionsWithEmptySolutions = solutions.flatMap(solution =>
        solution.solution.map((sol, index) => ({
            questionId: solution.id,
            solutionIndex: index,
            isEmpty: !sol.trim()
        })).filter(({ isEmpty }) => isEmpty)
    );
    if (questionsWithEmptySolutions.length > 0) {
        setAlerts(prev => {
            const filteredAlerts = prev.filter(alert => !alert.tag?.startsWith('empty-solution'));
            return [...filteredAlerts, ...questionsWithEmptySolutions.map(({ questionId, solutionIndex }) => ({
                variant: "error" as const,
                tag: `empty-solution-${questionId}-${solutionIndex}`,
                description: `Solution ${solutionIndex + 1} for question ${questionId} cannot be empty`
            }))];
        });
        return false;
    }
    setAlerts(prev => prev.filter(alert => !alert.tag?.startsWith('empty-solution')));
    return true;
};

const validateWordCount = (
    solutions: Array<{ id: string; solution: string[] }>,
    maxWords: number,
    setAlerts: React.Dispatch<React.SetStateAction<AlertItem[]>>
): boolean => {
    let isValid = true;
    solutions.forEach((solution) => {
        solution.solution.forEach((value, solutionIndex) => {
            const wordCount = value.trim().split(/\s+/).length;
            if (wordCount > maxWords) {
                isValid = false;
                setAlerts(prev => {
                    const filteredAlerts = prev.filter(alert =>
                        alert.tag !== `solution-error-${solution.id}-${solutionIndex}`
                    );
                    return [...filteredAlerts, {
                        variant: "error",
                        tag: `solution-error-${solution.id}-${solutionIndex}`,
                        description: `Solution ${solutionIndex + 1} for question ${solution.id} exceeds maximum of ${maxWords} words (current: ${wordCount} words)`
                    }];
                });
            } else {
                setAlerts(prev =>
                    prev.filter(alert =>
                        alert.tag !== `solution-error-${solution.id}-${solutionIndex}`
                    )
                );
            }
        });
    });
    return isValid;
};

export {
    validateQuestions,
    validateEmptySolutions,
    validateWordCount,
    validatePlaceholders
}
