import React, { useEffect, useState } from "react";
import { useRegisterMarkConfig } from "./RegisterMarkConfigProvider"; // Import the context hook

interface RegisterMarkProps {
    id: string; // Unique ID for the input
    initialValue: string; // Initial mark value
    onChange?: (value: string) => void; // Callback when value changes
    canChangeMarks?: boolean; // Permission to mark students
}

export const RegisterMark: React.FC<RegisterMarkProps> = ({
    id,
    initialValue,
    onChange,
    canChangeMarks = false
}) => {
    const [mark, setMark] = useState(initialValue || ""); // State for the current mark
    const config = useRegisterMarkConfig(); // Access shared config

    useEffect(() => {
        if (config) applyClasses(mark);
    }, [mark, config]);

    const cycleMark = () => {
        if (!canChangeMarks) return;

        if (!config) return;

        if (config.immutable.includes(mark)) return;

        const currentIndex = config.markable.indexOf(mark);
        const nextIndex = (currentIndex + 1) % config.markable.length;
        const nextMark = config.markable[nextIndex];

        setMark(nextMark);
        if (onChange) onChange(nextMark);
    };

    const applyClasses = (currentMark: string) => {
        const element = document.getElementById(id) as HTMLInputElement;

        if (!element || !config) return;

        const baseClasses = [...config.allowClasses];
        element.className = baseClasses.join(" ");

        const markClass = config.classes[currentMark] || "";
        if (markClass) element.classList.add(markClass);
    };

    const computedClassName = () => {
        if (!config) return "";

        const baseClasses = [...config.allowClasses];
        const markClass = config.classes[mark] || "";

        return [...baseClasses, markClass].join(" ").trim();
    };

    return (
        <input
            id={id}
            type="text"
            value={mark}
            size={1}
            className={computedClassName()}
            onClick={cycleMark}
            disabled={!config}
            readOnly // Explicitly make it read-only to silence any warnings
        />
    );
};

export default RegisterMark;
