import { useState, useEffect } from 'react';
import { NotifAlert, NotifOk } from '../../../../components/Global/ToastNotif';

export const useErrorCodeLogic = (errorCodeForm, fileList) => {
    const [solutionFields, setSolutionFields] = useState([0]);
    const [solutionTypes, setSolutionTypes] = useState({ 0: 'text' });
    const [solutionStatuses, setSolutionStatuses] = useState({ 0: true });
    const [firstSolutionValid, setFirstSolutionValid] = useState(false);
    const [solutionsToDelete, setSolutionsToDelete] = useState(new Set());

    const checkPreviousSolutionValid = (currentSolutionIndex) => {
        for (let i = 0; i < currentSolutionIndex; i++) {
            const fieldId = solutionFields[i];
            const solutionType = solutionTypes[fieldId];

            const solutionName = errorCodeForm.getFieldValue(`solution_name_${fieldId}`);
            if (!solutionName || solutionName.trim() === '') {
                return false;
            }

            if (solutionType === 'text') {
                const textSolution = errorCodeForm.getFieldValue(`text_solution_${fieldId}`);
                if (!textSolution || textSolution.trim() === '') {
                    return false;
                }
            } else if (solutionType === 'file') {
                const filesForSolution = fileList.filter(file => file.solutionId === fieldId);
                if (filesForSolution.length === 0) {
                    return false;
                }
            }
        }
        return true;
    };

    const checkFirstSolutionValid = () => {
        if (solutionFields.length === 0) {
            setFirstSolutionValid(false);
            return false;
        }
        const isValid = checkPreviousSolutionValid(1);
        setFirstSolutionValid(isValid);
        return isValid;
    };

    const handleAddSolutionField = () => {
        const currentSolutionCount = solutionFields.length;
        const nextSolutionNumber = currentSolutionCount + 1;

        if (!checkPreviousSolutionValid(currentSolutionCount)) {
            let incompleteSolutionIndex = -1;
            for (let i = 0; i < currentSolutionCount; i++) {
                const fieldId = solutionFields[i];
                const solutionType = solutionTypes[fieldId];
                const solutionName = errorCodeForm.getFieldValue(`solution_name_${fieldId}`);
                let hasContent = false;

                if (solutionType === 'text') {
                    const textSolution = errorCodeForm.getFieldValue(`text_solution_${fieldId}`);
                    hasContent = textSolution && textSolution.trim();
                } else if (solutionType === 'file') {
                    const filesForSolution = fileList.filter(file => file.solutionId === fieldId);
                    hasContent = filesForSolution.length > 0;
                }

                if (!solutionName?.trim() || !hasContent) {
                    incompleteSolutionIndex = i + 1;
                    break;
                }
            }

            NotifAlert({
                icon: 'warning',
                title: 'Perhatian',
                message: `Harap lengkapi Solution ${incompleteSolutionIndex} terlebih dahulu sebelum menambah Solution ${nextSolutionNumber}!`
            });
            return;
        }

        const newId = `new-${Date.now()}`;
        setSolutionFields(prev => [...prev, newId]);
        setSolutionTypes(prev => ({ ...prev, [newId]: 'text' }));
        setSolutionStatuses(prev => ({ ...prev, [newId]: true }));
        errorCodeForm.setFieldValue(`solution_status_${newId}`, true);
        errorCodeForm.setFieldValue(`solution_type_${newId}`, 'text');
    };

    const handleRemoveSolutionField = (id) => {
        const isNewSolution = !id.toString().startsWith('existing-');

        if (isNewSolution) {
            if (solutionFields.length > 1) {
                setSolutionFields(solutionFields.filter(fieldId => fieldId !== id));
                setSolutionTypes(prev => {
                    const newTypes = { ...prev };
                    delete newTypes[id];
                    return newTypes;
                });
                setSolutionStatuses(prev => {
                    const newStatuses = { ...prev };
                    delete newStatuses[id];
                    return newStatuses;
                });
                setSolutionsToDelete(prev => {
                    const newSet = new Set(prev);
                    newSet.delete(id);
                    return newSet;
                });
            } else {
                NotifAlert({
                    icon: 'warning',
                    title: 'Perhatian',
                    message: 'Setiap error code harus memiliki minimal 1 solution!'
                });
            }
        } else {
            const solutionName = errorCodeForm.getFieldValue(`solution_name_${id}`);
            const solutionType = solutionTypes[id];
            let isEmpty = true;

            const existingSolution = window.currentSolutionData?.[id];
            const hasExistingData = existingSolution && (
                (existingSolution.solution_name && existingSolution.solution_name.trim()) ||
                (existingSolution.text_solution && existingSolution.text_solution.trim()) ||
                (existingSolution.path_solution && existingSolution.path_solution.trim())
            );

            if (solutionType === 'text') {
                const textSolution = errorCodeForm.getFieldValue(`text_solution_${id}`);
                isEmpty = !solutionName?.trim() && !textSolution?.trim() && !hasExistingData;
            } else if (solutionType === 'file') {
                const filesForSolution = fileList.filter(file => file.solutionId === id);
                isEmpty = !solutionName?.trim() && filesForSolution.length === 0 && !hasExistingData;
            }

            if (isEmpty) {
                if (solutionFields.length > 1) {
                    setSolutionFields(solutionFields.filter(fieldId => fieldId !== id));
                    setSolutionTypes(prev => {
                        const newTypes = { ...prev };
                        delete newTypes[id];
                        return newTypes;
                    });
                    setSolutionStatuses(prev => {
                        const newStatuses = { ...prev };
                        delete newStatuses[id];
                        return newStatuses;
                    });

                    if (window.currentSolutionData) {
                        delete window.currentSolutionData[id];
                    }

                    setSolutionsToDelete(prev => {
                        const newSet = new Set(prev);
                        newSet.delete(id);
                        return newSet;
                    });
                } else {
                    NotifAlert({
                        icon: 'warning',
                        title: 'Perhatian',
                        message: 'Setiap error code harus memiliki minimal 1 solution!'
                    });
                }
            } else {
                if (solutionFields.length > 1) {
                    setSolutionsToDelete(prev => new Set(prev).add(id));

                    const solutionElement = document.querySelector(`[data-solution-id="${id}"]`);
                    if (solutionElement) {
                        solutionElement.style.opacity = '0.5';
                        solutionElement.style.border = '2px dashed #ff4d4f';
                    }

                    NotifOk({
                        icon: 'success',
                        title: 'Berhasil',
                        message: 'Solution ditandai untuk dihapus. Klik "Update Error Code" untuk menyimpan perubahan.'
                    });
                } else {
                    NotifAlert({
                        icon: 'warning',
                        title: 'Perhatian',
                        message: 'Setiap error code harus memiliki minimal 1 solution!'
                    });
                }
            }
        }
    };

    const handleSolutionTypeChange = (fieldId, type) => {
        setSolutionTypes(prev => ({ ...prev, [fieldId]: type }));
    };

    const handleSolutionStatusChange = (fieldId, status) => {
        setSolutionStatuses(prev => ({
            ...prev,
            [fieldId]: status
        }));
    };

    const setSolutionsForExistingRecord = (solutions, errorCodeForm) => {
        const newSolutionFields = [];
        const newSolutionTypes = {};
        const newSolutionStatuses = {};
        const newSolutionData = {};

        solutions.forEach((solution, index) => {
            const fieldId = `existing-${index}`;
            newSolutionFields.push(fieldId);
            newSolutionTypes[fieldId] = solution.type_solution || 'text';
            newSolutionStatuses[fieldId] = solution.is_active !== false;
            newSolutionData[fieldId] = {
                ...solution
            };

            setTimeout(() => {
                errorCodeForm.setFieldsValue({
                    [`solution_name_${fieldId}`]: solution.solution_name,
                    [`text_solution_${fieldId}`]: solution.text_solution || '',
                    [`solution_status_${fieldId}`]: solution.is_active !== false,
                    [`solution_type_${fieldId}`]: solution.type_solution === 'image' || solution.type_solution === 'pdf' ? 'file' : solution.type_solution
                });
            }, 100);
        });

        setSolutionFields(newSolutionFields);
        setSolutionTypes(newSolutionTypes);
        setSolutionStatuses(newSolutionStatuses);
        window.currentSolutionData = newSolutionData;
    };

    const resetSolutionFields = () => {
        setSolutionFields([0]);
        setSolutionTypes({ 0: 'text' });
        setSolutionStatuses({ 0: true });
        setFirstSolutionValid(false);
        setSolutionsToDelete(new Set());
    };

    useEffect(() => {
        const timer = setTimeout(() => {
            checkFirstSolutionValid();
        }, 100);
        return () => clearTimeout(timer);
    }, [solutionFields, solutionTypes, fileList, errorCodeForm]);

    return {
        solutionFields,
        solutionTypes,
        solutionStatuses,
        firstSolutionValid,
        solutionsToDelete,
        handleAddSolutionField,
        handleRemoveSolutionField,
        handleSolutionTypeChange,
        handleSolutionStatusChange,
        resetSolutionFields,
        checkFirstSolutionValid,
        setSolutionsForExistingRecord
    };
};