import { useState } from 'react';

export const useSparepartLogic = (sparepartForm) => {
    const [sparepartFields, setSparepartFields] = useState([
        { name: ['sparepart_items', 0], key: 0 }
    ]);
    const [sparepartTypes, setSparepartTypes] = useState({ 0: 'required' });
    const [sparepartStatuses, setSparepartStatuses] = useState({ 0: true });

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

        setSparepartFields(prev => [...prev, newField]);
        setSparepartTypes(prev => ({ ...prev, [newKey]: 'required' }));
        setSparepartStatuses(prev => ({ ...prev, [newKey]: true }));

        // Set default values for the new field
        setTimeout(() => {
            sparepartForm.setFieldValue(['sparepart_items', newKey, 'type'], 'required');
            sparepartForm.setFieldValue(['sparepart_items', newKey, 'quantity'], 1);
        }, 0);
    };

    const handleRemoveSparepartField = (key) => {
        if (sparepartFields.length <= 1) {
            return; // Keep at least one sparepart field
        }

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

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

        setSparepartTypes(newTypes);
        setSparepartStatuses(newStatuses);
    };

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

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

    const resetSparepartFields = () => {
        setSparepartFields([{ name: ['sparepart_items', 0], key: 0 }]);
        setSparepartTypes({ 0: 'required' });
        setSparepartStatuses({ 0: true });

        // Reset form values
        sparepartForm.resetFields();
        sparepartForm.setFieldsValue({
            sparepart_status_0: true,
            sparepart_type_0: 'required',
        });
    };

    const getSparepartData = () => {
        const values = sparepartForm.getFieldsValue();
        return sparepartFields.map(field => {
            const key = field.key;
            const sparepartPath = field.name.join(',');
            const sparepart = values[sparepartPath];

            return sparepart && sparepart.name && sparepart.name.trim() !== '' ? {
                name: sparepart.name || '',
                description: sparepart.description || '',
                is_active: sparepart.status !== false,
            } : null;
        }).filter(Boolean);
    };

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

        const newFields = spareparts.map((sparepart, index) => ({
            name: ['sparepart_items', sparepart.id || index],
            key: sparepart.id || index
        }));

        setSparepartFields(newFields);

        // Set sparepart values
        const formValues = {};
        Object.keys(spareparts).forEach(index => {
            const key = spareparts[index].id || index;
            const sparepart = spareparts[index];
            formValues[`sparepart_items,${key}`] = {
                name: sparepart.name || '',
                description: sparepart.description || '',
                status: sparepart.is_active !== false,
            };
        });

        form.setFieldsValue(formValues);
    };

    return {
        sparepartFields,
        sparepartTypes,
        sparepartStatuses,
        handleAddSparepartField,
        handleRemoveSparepartField,
        handleSparepartTypeChange,
        handleSparepartStatusChange,
        resetSparepartFields,
        getSparepartData,
        setSparepartForExistingRecord,
    };
};