import { useState, useEffect } from 'react';

export const useSolutionLogic = (solutionForm) => {
    const [solutionFields, setSolutionFields] = useState([0]);
    const [solutionTypes, setSolutionTypes] = useState({ 0: 'text' });
    const [solutionStatuses, setSolutionStatuses] = useState({ 0: true });
    const [solutionsToDelete, setSolutionsToDelete] = useState([]);

    useEffect(() => {
        setTimeout(() => {
            if (solutionForm) {
                solutionForm.setFieldsValue({
                    solution_items: {
                        0: {
                            name: 'Solution 1',
                            status: true,
                            type: 'text',
                            text: 'Solution description',
                            file: null,
                            fileUpload: null
                        }
                    }
                });
            }
        }, 100);
    }, [solutionForm]);

    const handleAddSolutionField = () => {
        const newKey = Date.now();

        setSolutionFields(prev => [...prev, newKey]);
        setSolutionTypes(prev => ({ ...prev, [newKey]: 'text' }));
        setSolutionStatuses(prev => ({ ...prev, [newKey]: true }));

        setTimeout(() => {
            const currentFormValues = solutionForm.getFieldsValue(true);
            const existingNames = [];

            Object.keys(currentFormValues).forEach(key => {
                if (key.startsWith('solution_items,') || key.startsWith('solution_items.')) {
                    const solutionData = currentFormValues[key];
                    if (solutionData && solutionData.name) {
                        existingNames.push(solutionData.name);
                    }
                }
            });

            if (currentFormValues.solution_items) {
                Object.values(currentFormValues.solution_items).forEach(solution => {
                    if (solution && solution.name) {
                        existingNames.push(solution.name);
                    }
                });
            }

            let solutionNumber = solutionFields.length + 1;
            let defaultName = `Solution ${solutionNumber}`;

            while (existingNames.includes(defaultName)) {
                solutionNumber++;
                defaultName = `Solution ${solutionNumber}`;
            }

            solutionForm.setFieldValue(['solution_items', newKey, 'name'], defaultName);
            solutionForm.setFieldValue(['solution_items', newKey, 'type'], 'text');
            solutionForm.setFieldValue(['solution_items', newKey, 'text'], 'Solution description');
            solutionForm.setFieldValue(['solution_items', newKey, 'status'], true);
            solutionForm.setFieldValue(['solution_items', newKey, 'file'], null);
            solutionForm.setFieldValue(['solution_items', newKey, 'fileUpload'], null);
        }, 100);
    };

    const handleRemoveSolutionField = (key) => {
        if (solutionFields.length <= 1) {
            return;
        }

        setSolutionFields(prev => prev.filter(field => field !== key));

        const newTypes = { ...solutionTypes };
        const newStatuses = { ...solutionStatuses };
        delete newTypes[key];
        delete newStatuses[key];

        setSolutionTypes(newTypes);
        setSolutionStatuses(newStatuses);

        setTimeout(() => {
            try {
                solutionForm.setFieldValue(['solution_items', key], undefined);
                solutionForm.setFieldValue(['solution_items', key, 'name'], undefined);
                solutionForm.setFieldValue(['solution_items', key, 'type'], undefined);
                solutionForm.setFieldValue(['solution_items', key, 'text'], undefined);
                solutionForm.setFieldValue(['solution_items', key, 'status'], undefined);
                solutionForm.setFieldValue(['solution_items', key, 'file'], undefined);
                solutionForm.setFieldValue(['solution_items', key, 'fileUpload'], undefined);
            } catch (error) {
            }
        }, 50);
    };

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

        setTimeout(() => {
            const fieldName = ['solution_items', key];
            const currentSolutionData = solutionForm.getFieldsValue([fieldName]) || {};
            const solutionData = currentSolutionData[`solution_items,${key}`] || currentSolutionData[`solution_items.${key}`] || {};

            if (value === 'text') {
                const updatedSolutionData = {
                    ...solutionData,
                    fileUpload: null,
                    file: null,
                    path_solution: null,
                    fileName: null,
                    text: solutionData.text || 'Solution description'
                };

                solutionForm.setFieldValue([...fieldName, 'fileUpload'], null);
                solutionForm.setFieldValue([...fieldName, 'file'], null);
                solutionForm.setFieldValue([...fieldName, 'path_solution'], null);
                solutionForm.setFieldValue([...fieldName, 'fileName'], null);
                solutionForm.setFieldValue([...fieldName, 'text'], updatedSolutionData.text);
            } else if (value === 'file') {
                const updatedSolutionData = {
                    ...solutionData,
                    text: '',
                    fileUpload: null,
                    file: null,
                    path_solution: null,
                    fileName: null
                };
                solutionForm.setFieldValue([...fieldName, 'text'], '');
                solutionForm.setFieldValue([...fieldName, 'fileUpload'], null);
                solutionForm.setFieldValue([...fieldName, 'file'], null);
                solutionForm.setFieldValue([...fieldName, 'path_solution'], null);
                solutionForm.setFieldValue([...fieldName, 'fileName'], null);
            }
        }, 0);
    };

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

    const resetSolutionFields = () => {
        setSolutionFields([0]);
        setSolutionTypes({ 0: 'text' });
        setSolutionStatuses({ 0: true });

        if (!solutionForm || !solutionForm.resetFields) {
            return;
        }

        solutionForm.resetFields();
        setTimeout(() => {
            solutionForm.setFieldsValue({
                solution_items: {
                    0: {
                        name: 'Solution 1',
                        status: true,
                        type: 'text',
                        text: 'Solution description',
                        file: null,
                        fileUpload: null
                    }
                }
            });

            solutionForm.setFieldValue(['solution_items', 0, 'name'], 'Solution 1');
            solutionForm.setFieldValue(['solution_items', 0, 'type'], 'text');
            solutionForm.setFieldValue(['solution_items', 0, 'text'], 'Solution description');
            solutionForm.setFieldValue(['solution_items', 0, 'status'], true);
            solutionForm.setFieldValue(['solution_items', 0, 'file'], null);
            solutionForm.setFieldValue(['solution_items', 0, 'fileUpload'], null);

        }, 100);
    };

    const checkFirstSolutionValid = () => {
        if (!solutionForm || !solutionForm.getFieldsValue) {
            return false;
        }
        const values = solutionForm.getFieldsValue();

        const firstField = solutionFields[0];
        if (!firstField) {
            return false;
        }

        const solutionKey = firstField.key || firstField;
        const commaPath = `solution_items,${solutionKey}`;
        const dotPath = `solution_items.${solutionKey}`;
        const firstSolution = values[commaPath] || values[dotPath];

        if (!firstSolution || !firstSolution.name || firstSolution.name.trim() === '') {
            return false;
        }

        if (solutionTypes[solutionKey] === 'text' && (!firstSolution.text || firstSolution.text.trim() === '')) {
            return false;
        }

        return true;
    };

    const getSolutionData = () => {
        try {
            const values = solutionForm.getFieldsValue(true);
            const result = [];

            solutionFields.forEach(key => {
                let solution = null;

                try {
                    solution = solutionForm.getFieldValue(['solution_items', key]);
                } catch (error) {
                }

                if (!solution && values.solution_items && values.solution_items[key]) {
                    solution = values.solution_items[key];
                }

                if (!solution) {
                    const commaKey = `solution_items,${key}`;
                    solution = values[commaKey];
                }

                if (!solution) {
                    const dotKey = `solution_items.${key}`;
                    solution = values[dotKey];
                }

                if (!solution) {
                    const allKeys = Object.keys(values);
                    const foundKey = allKeys.find(k =>
                        k.includes(key.toString()) &&
                        k.includes('solution_items')
                    );
                    if (foundKey) {
                        solution = values[foundKey];
                    }
                }

                if (!solution) {
                    const rawValues = solutionForm.getFieldsValue();

                    if (rawValues.solution_items && rawValues.solution_items[key]) {
                        solution = rawValues.solution_items[key];
                    }
                }

                if (!solution) {
                    return;
                }


                const hasName = solution.name && solution.name.trim() !== '';

                if (!hasName) {
                    return;
                }

                const solutionType = solutionTypes[key] || solution.type || 'text';
                let isValidType = true;

                if (solutionType === 'text') {
                    isValidType = solution.text && solution.text.trim() !== '';
                    if (!isValidType) {
                        return;
                    }
                } else if (solutionType === 'file') {
                    const hasPathSolution = solution.path_solution && solution.path_solution.trim() !== '';
                    const hasFileUpload = (solution.fileUpload && typeof solution.fileUpload === 'object' && Object.keys(solution.fileUpload).length > 0);
                    const hasFile = (solution.file && typeof solution.file === 'object' && Object.keys(solution.file).length > 0);

                    isValidType = hasPathSolution || hasFileUpload || hasFile;
                    if (!isValidType) {
                        return;
                    }
                }

                let pathSolution = '';
                let fileObject = null;
                const typeSolution = solutionTypes[key] || solution.type || 'text';

                if (typeSolution === 'file') {
                    if (solution.fileUpload && typeof solution.fileUpload === 'object' && Object.keys(solution.fileUpload).length > 0) {
                        pathSolution = solution.fileUpload.path_solution || solution.fileUpload.uploadPath || '';
                        fileObject = solution.fileUpload;
                    } else if (solution.file && typeof solution.file === 'object' && Object.keys(solution.file).length > 0) {
                        pathSolution = solution.file.path_solution || solution.file.uploadPath || '';
                        fileObject = solution.file;
                    } else if (solution.file && typeof solution.file === 'string' && solution.file.trim() !== '') {
                        pathSolution = solution.file;
                    } else if (solution.path_solution && solution.path_solution.trim() !== '') {
                        pathSolution = solution.path_solution;
                    } else {
                    }
                }

                let finalTypeSolution = typeSolution;
                if (typeSolution === 'file') {
                    if (fileObject && fileObject.type_solution) {
                        finalTypeSolution = fileObject.type_solution;
                    } else {
                        finalTypeSolution = 'image';
                    }
                }

                const finalSolution = {
                    solution_name: solution.name,
                    type_solution: finalTypeSolution,
                    is_active: solution.status !== false && solution.status !== undefined ? solution.status : (solutionStatuses[key] !== false),
                };

                if (typeSolution === 'text') {
                    finalSolution.text_solution = solution.text || '';
                    finalSolution.path_solution = '';
                } else {
                    finalSolution.text_solution = '';
                    finalSolution.path_solution = pathSolution;
                }

                result.push(finalSolution);
            });

            return result;
        } catch (error) {
            return [];
        }
    };

    const setSolutionsForExistingRecord = (solutions, form) => {
        if (!solutions || solutions.length === 0) return;

        const newFields = solutions.map((solution, index) => solution.id || index);

        setSolutionFields(newFields);

        const solutionsValues = {};
        const newTypes = {};
        const newStatuses = {};

        solutions.forEach((solution, index) => {
            const key = solution.brand_code_solution_id || solution.id || index;

            let fileObject = null;
            if (solution.path_solution && solution.path_solution.trim() !== '') {
                const fileName = solution.file_upload_name || solution.path_solution.split('/').pop() || `file_${index}`;

                fileObject = {
                    uploadPath: solution.path_solution,
                    path_solution: solution.path_solution,
                    name: fileName,
                    type_solution: solution.type_solution || 'image',
                    isExisting: true,
                    size: 0,
                    type: solution.type_solution === 'pdf' ? 'application/pdf' : 'image/jpeg',
                    fileExtension: solution.type_solution === 'pdf' ? 'pdf' : (fileName.split('.').pop().toLowerCase() || 'jpg')
                };
            }

            const isFileType = solution.type_solution && solution.type_solution !== 'text' && fileObject;

            solutionsValues[key] = {
                name: solution.solution_name || '',
                type: isFileType ? 'file' : 'text',
                text: solution.text_solution || '',
                file: fileObject,
                fileUpload: fileObject,
                status: solution.is_active !== false,
                path_solution: solution.path_solution || ''
            };
            newTypes[key] = isFileType ? 'file' : 'text';
            newStatuses[key] = solution.is_active !== false;
        });

        const nestedFormValues = {
            solution_items: {}
        };

        Object.keys(solutionsValues).forEach(key => {
            const solution = solutionsValues[key];
            nestedFormValues.solution_items[key] = {
                name: solution.name,
                type: solution.type,
                text: solution.text,
                file: solution.file,
                fileUpload: solution.fileUpload,
                status: solution.status,
                path_solution: solution.path_solution
            };
        });

        form.setFieldsValue(nestedFormValues);

        const fallbackFormValues = {};
        Object.keys(solutionsValues).forEach(key => {
            const solution = solutionsValues[key];
            fallbackFormValues[`solution_items,${key}`] = {
                name: solution.name,
                type: solution.type,
                text: solution.text,
                file: solution.file,
                fileUpload: solution.fileUpload,
                status: solution.status,
                path_solution: solution.path_solution
            };
        });

        form.setFieldsValue(fallbackFormValues);

        Object.keys(solutionsValues).forEach(key => {
            const solution = solutionsValues[key];
            form.setFieldValue([`solution_items,${key}`, 'name'], solution.name);
            form.setFieldValue([`solution_items,${key}`, 'type'], solution.type);
            form.setFieldValue([`solution_items,${key}`, 'text'], solution.text);
            form.setFieldValue([`solution_items,${key}`, 'file'], solution.file);
            form.setFieldValue([`solution_items,${key}`, 'fileUpload'], solution.fileUpload);
            form.setFieldValue([`solution_items,${key}`, 'status'], solution.status);
            form.setFieldValue([`solution_items,${key}`, 'path_solution'], solution.path_solution);

            form.setFieldValue(['solution_items', key, 'name'], solution.name);
            form.setFieldValue(['solution_items', key, 'type'], solution.type);
            form.setFieldValue(['solution_items', key, 'text'], solution.text);
            form.setFieldValue(['solution_items', key, 'file'], solution.file);
            form.setFieldValue(['solution_items', key, 'fileUpload'], solution.fileUpload);
            form.setFieldValue(['solution_items', key, 'status'], solution.status);
            form.setFieldValue(['solution_items', key, 'path_solution'], solution.path_solution);
        });

        setSolutionTypes(newTypes);
        setSolutionStatuses(newStatuses);
    };

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