import { CheckCircleFilled, ExclamationCircleOutlined, SyncOutlined, WarningOutlined } from '@ant-design/icons';
import React from 'react';
import { z } from 'zod';

const TableRecordValidation = z.object({
    question: z.string(),
    explanation: z.string().optional(),
    complexity: z.string().length(1),
    category: z.number().int().positive(),
    subject: z.number().int().positive()
});

const Option = z.object({
    text: z.string(),
    isCorrect: z.boolean(),
});

const UseValidation = ({record, index, tableData, setTableData}) => {

    const SpecificTableQuestionShape = z.discriminatedUnion('type', [
        // type : "MCQ"
        z.object({
            type: z.literal("MCQ"),
            answer: z.array(z.string()).length(1, "Can not have more/less than one answer in 'MCQ' type questions."),
            options: z.array(Option).min(2, "Options can not be less than two!").max(6, "Options are more than six!"),
        }),
        // type : "MRQ"
        z.object({
            type: z.literal("MRQ"),
            answer: z.array(z.string()).min(2, "Can not have less than two answer in 'MRQ' type questions")
                .max(6, "Can not have more than six answer in 'MRQ' type questions"),
            options: z.array(Option).min(2, "Options can not be less than two!").max(6, "Options are more than six!"),
        }),
        // type: "TNF"
        z.object({
            type: z.literal("TNF"),
            answer: z.array(z.string()).length(1, "Can not have more/less than one answer in 'TNF' type questions."),
            options: z.array(Option).length(2, "True and False Questions can only have two options!")
        })
    ])
    .and(TableRecordValidation)
    .superRefine((val,ctx) => {
        const {answer, options, type} = val;
        // console.log("------------>", answer, options); // dev-log
        if(type !== "TNF") {
            for(let item of answer) {
                if(item > options.length) {   // dev logic, change it to proper logic
                    ctx.addIssue({
                        code: z.ZodIssueCode.too_big,
                        maximum: options.length,
                        type: "number",
                        inclusive: true,
                        message: "An item in answer array is greater than number of options available.",
                        path: ["answer"]
                    });
                }
            }
        } else {
            if(!(answer[0] === "true" || answer[0] === "false")) {
                ctx.addIssue({
                    code: z.ZodIssueCode.custom,
                    message: "The answer for TNF question is something other than true or false.",
                    path: ["answer"]
                });
            }
        }
    });
    
    React.useEffect(() => {
        let timeoutHolder;
        // console.log(record.validated, record.key);
        if(record.validated === "processing") {
            timeoutHolder = setTimeout(() => toCheckValidity(record));
        }
        return () => {
            clearTimeout(timeoutHolder);
        }
    }, [record]);

    async function toCheckValidity(record) {
        try {
            const validCheck = await SpecificTableQuestionShape.parse(record);
            if(validCheck) {
                setTableData(prev => {
                    prev[record.key].validated = true;
                    return [...prev];
                })
            }
            // return validCheck;
        } catch (error) {
            // process.env.NODE_ENV==="development" && console.log(record.key + " is Invalidated! ", error);
            // tableData[index].validated = false;
            setTableData(prev => {
                prev[record.key].validated = false;
                return [...prev];
            })
        }
    }

    if(record.validated === true) {
        return <CheckCircleFilled style={{color: "blue", size: 14}}/>
    }
    if(record.validated === false) {
        return <ExclamationCircleOutlined style={{color: "red", size: 14}}/>
    }
    return <SyncOutlined spin style={{color: "orangered", size: 14}}/>
}

export default UseValidation;
