import { useState, useEffect } from 'react';
import materialService from '../services/serviceMaterials';
import { MEDIA_URL } from '../../../../utils/Constant';

const useUpdateMaterials = (materialId) => {
    const [materialData, setMaterialData] = useState([]);
    const [levelName, setLevelName] = useState('Level');
    const [sectionName, setSectionName] = useState('section');
    const [topicName, setTopicName] = useState('topic');
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const mediaPath = `${MEDIA_URL}/level`;

    const [formData, setFormData] = useState({
        content: '',
        audio:  '',
        image: '',
        video: ''
    });

    const [showLoader, setShowLoader] = useState(false);
    const [loaderState, setLoaderState] = useState({ loading: false, successMessage: '', title: '', description: '', confirmAction: false });

    const handleFormChange = (e) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
    };

    const [audioPreview, setAudioPreview] = useState(null);
    const [audioPreviewTitle, setAudioPreviewTitle] = useState(null);
    const handleFormChangeAudio = (e) => {
        setAudioPreviewTitle(e.target.value);
        const file = e.target.files[0]; 
        if (file) {
            const mediaUrl = URL.createObjectURL(file); 
            setAudioPreview(mediaUrl); 
        }
        setFormData({ ...formData, [e.target.name]: file });
    };

    const [imagePreview, setImagePreview] = useState(null);
    const [imagePreviewTitle, setImagePreviewTitle] = useState('');
    const handleFormChangeImage = (e) => {
        setImagePreviewTitle(e.target.value);
        const file = e.target.files[0]; 
        if (file) {
            const mediaUrl = URL.createObjectURL(file); 
            setImagePreview(mediaUrl); 
        }
        setFormData({ ...formData, [e.target.name]: file });
    };

    const handleRemoveMedia = (type) =>{
        setFormData({ ...formData, [type]: '' });
        if (type === 'image') {
            setImagePreview('');
            setImagePreviewTitle('');
            setMaterialData({...materialData, IMAGE:""});
        }else{
            setAudioPreview('');
            setAudioPreviewTitle('');
            setMaterialData({...materialData, AUDIO:""});
        }
    };

    const handleCloseLoader = () => setShowLoader(false);
    const handleShowLoader = (title, description, loading = false, successMessage = '', confirmAction = false) => {
        setLoaderState({ title, description, loading, successMessage, confirmAction });
        setShowLoader(true);
    };

    const updateMaterials = async () => {
        const id = materialData.ID_LEVEL;

        const updateData = new FormData();
        updateData.append('CONTENT', formData.content,);
        if (formData.audio) {
            updateData.append('AUDIO', formData.audio);
        }
        if (formData.image) {
            updateData.append('IMAGE', formData.image);
        }
        if (formData.video) {
            updateData.append('VIDEO', formData.video);
        }

        handleShowLoader('Updated', '', true);
        try {
            const update = await materialService.updateData(id, updateData);
            setMaterialData(update.payload);
            setFormData({
                content: update.payload.CONTENT,
                audio:  update.payload.AUDIO,
                image: update.payload.IMAGE,
                video: update.payload.VIDEO
            });
            setLoaderState(prev => ({
                ...prev,
                loading: false,
                successMessage: 'Your data has been successfully updated.'
            }));
        } catch (err) {
            // setError(err);
            setLoaderState(prev => ({
                ...prev,
                title: "ERROR",
                loading: false,
                successMessage: err.message
            }));
        }
    };

    useEffect(() => {
        const fetchData = async () => {
            setLoading(true);
            try {
                const data = await materialService.getLevelById(materialId);
                setLevelName(data.payload.NAME_LEVEL);
                setSectionName(data.payload.NAME_SECTION);
                setTopicName(data.payload.NAME_TOPIC);
                setMaterialData(data.payload);
                setFormData({
                    content: data.payload.CONTENT,
                    audio:  data.payload.AUDIO,
                    image: data.payload.IMAGE,
                    video: data.payload.VIDEO
                });
            } catch (error) {
                setError(error);
            } finally {
                setLoading(false);
            }
        };

        fetchData();
    }, [materialId]);

    return { 
        materialData, 
        formData, 
        levelName,
        sectionName, 
        topicName, 
        loading, 
        error, 
        mediaPath, 
        audioPreview,
        imagePreview,
        audioPreviewTitle,
        imagePreviewTitle,
        handleFormChange, 
        handleFormChangeAudio,
        handleFormChangeImage,
        handleRemoveMedia,
        updateMaterials,
        showLoader,
        handleCloseLoader,
        loaderState,
    };
};

export default useUpdateMaterials;