import { useState } from 'react';

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

    const handleAddSolutionField = () => {
        const newKey = Date.now(); // Use timestamp for unique key
        const newField = { name: ['solution_items', newKey], key: newKey };

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

        // Set default values for the new field
        setTimeout(() => {
            solutionForm.setFieldValue(['solution_items', newKey, 'name'], '');
            solutionForm.setFieldValue(['solution_items', newKey, 'type'], 'text');
            solutionForm.setFieldValue(['solution_items', newKey, 'text'], '');
        }, 0);
    };

    const handleRemoveSolutionField = (key) => {
        if (solutionFields.length <= 1) {
            return; // Keep at least one solution field
        }

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

        // Clean up type and status
        const newTypes = { ...solutionTypes };
        const newStatuses = { ...solutionStatuses };
        delete newTypes[key];
        delete newStatuses[key];

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

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

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

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

        // Reset form values
        solutionForm.resetFields();
        solutionForm.setFieldsValue({
            solution_status_0: true,
            solution_type_0: 'text',
        });
    };

    const checkFirstSolutionValid = () => {
        const values = solutionForm.getFieldsValue();
        const firstSolution = values.solution_items?.[0];

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

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

        return true;
    };

    const getSolutionData = () => {
        const values = solutionForm.getFieldsValue();

        const result = solutionFields.map(field => {
            const key = field.key;
            // Access form values using the key from field.name (AntD stores with comma)
            const solutionPath = field.name.join(',');
            const solution = values[solutionPath];

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

            if (validSolution) {
                return {
                    solution_name: solution.name || 'Default Solution',
                    type_solution: solutionTypes[key] || 'text',
                    text_solution: solution.text || '',
                    path_solution: solution.file || '',
                    is_active: solution.status !== false, // Use form value directly
                };
            }
            return null;
        }).filter(Boolean);

        return result;
    };

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

        const newFields = solutions.map((solution, index) => ({
            name: ['solution_items', solution.id || index],
            key: solution.id || index
        }));

        setSolutionFields(newFields);

        // Set solution values
        const solutionsValues = {};
        const newTypes = {};
        const newStatuses = {};

        solutions.forEach((solution, index) => {
            const key = solution.id || index;
            solutionsValues[key] = {
                name: solution.solution_name || '',
                type: solution.type_solution || 'text',
                text: solution.text_solution || '',
                file: solution.path_solution || '',
            };
            newTypes[key] = solution.type_solution || 'text';
            newStatuses[key] = solution.is_active !== false;
        });

        // Set all form values at once
        const formValues = {};
        Object.keys(solutionsValues).forEach(key => {
            const solution = solutionsValues[key];
            formValues[`solution_items,${key}`] = {
                name: solution.name,
                type: solution.type,
                text: solution.text,
                file: solution.file,
                status: solution.is_active !== false
            };
        });

        form.setFieldsValue(formValues);
        setSolutionTypes(newTypes);
        setSolutionStatuses(newStatuses);
    };

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