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

const useTest = (materialId) => {
    const [editorData, setEditorData] = 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 editorContainerRef = useRef(null);
	const editorRef = useRef(null);
	const [isLayoutReady, setIsLayoutReady] = useState(false);
    const mediaPath = `${MEDIA_URL}/level/`;
    
    const [show, setShow] = useState(false);

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

    const handleEditorChange = (event, editor) => {
        const data = editor.getData();
        setEditorData(data);
    };

    const mediaUpload = async (type, file) => {
        setShow(true);
        const mediaData = new FormData();
        mediaData.append(`${type}[0]`, file); 

        try {
            const upload = await materialService.uploadMedia(materialId, mediaData);

            const fileName = upload.payload[`${type}[0]`];
            const url = `${mediaPath}${type.toLowerCase()}/${fileName}`

            setShow(false);
            return url;
        } catch (err) {
            return err;
        }
    };
	
	class MyUploadAdapter {
		constructor(loader, apiUrl) {
			this.loader = loader;
			this.apiUrl = apiUrl;
		}

		upload() {
			return this.loader.file
				.then(file => new Promise(async (resolve, reject) => {
					try {
						const imageUrl = await mediaUpload('IMAGE', file);
						resolve({
							default: imageUrl  
						});
					} catch (error) {
						reject(error.message);  
					}
				}));
		}

		// Handle abort saat upload
		abort() {
			// Implementasikan jika ingin support untuk membatalkan upload
		}
	}

	function CustomUploadAdapterPlugin (editor) {
		editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
			return new MyUploadAdapter(loader, 'https://');
		};
	}

	// function CustomMediaPlugin (editor) {
	// 	// Plugin untuk Audio
	// 	editor.ui.componentFactory.add('audioUpload', locale => {
	// 		const view = new ButtonView(locale);

	// 		const audioIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-file-earmark-music" viewBox="0 0 16 16"><path d="M11 6.64a1 1 0 0 0-1.243-.97l-1 .25A1 1 0 0 0 8 6.89v4.306A2.6 2.6 0 0 0 7 11c-.5 0-.974.134-1.338.377-.36.24-.662.628-.662 1.123s.301.883.662 1.123c.364.243.839.377 1.338.377s.974-.134 1.338-.377c.36-.24.662-.628.662-1.123V8.89l2-.5z"/><path d="M14 14V4.5L9.5 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2M9.5 3A1.5 1.5 0 0 0 11 4.5h2V14a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h5.5z"/></svg>` 

	// 		view.set({
	// 			label: '',
	// 			icon: audioIcon,  
	// 			withText: false,  
	// 			tooltip: 'Upload Audio'  
	// 		});

	// 		view.on('execute', () => {
	// 			const input = document.createElement('input');
	// 			input.type = 'file';
	// 			input.accept = 'audio/*';  

	// 			input.onchange = async () => {
	// 				const file = input.files[0];
	// 				if (file) {
	// 					try {
	// 						const audioUrl = await mediaUpload('AUDIO', file);
	// 						editor.model.change(writer => {
	// 							const audioElement = writer.createElement('audio', {
	// 								src: audioUrl
	// 							});
	// 							editor.model.insertContent(audioElement, editor.model.document.selection);
	// 						});
	// 					} catch (error) {
	// 						console.error('Error uploading audio:', error);
	// 					}
	// 				}
	// 			};

	// 			input.click();
	// 		});

	// 		return view;
	// 	});
	// 	// Plugin untuk Image
	// 	editor.ui.componentFactory.add('imageUpload', locale => {
	// 		const view = new ButtonView(locale);

	// 		view.set({
	// 			label: 'image',  
	// 			withText: true,  
	// 			tooltip: 'Upload Image'  
	// 		});

	// 		view.on('execute', () => {
	// 			const input = document.createElement('input');
	// 			input.type = 'file';
	// 			input.accept = 'image/*';  // Menerima file gambar

	// 			input.onchange = async () => {
	// 				const file = input.files[0];
	// 				if (file) {
	// 					try {
	// 						const imageUrl = await mediaUpload('IMAGE', file);
	// 						editor.model.change(writer => {
	// 							const imageElement = writer.createElement('image', {
	// 								src: imageUrl
	// 							});
	// 							editor.model.insertContent(imageElement, editor.model.document.selection);
	// 						});
	// 					} catch (error) {
	// 						console.error('Error uploading image:', error);
	// 					}
	// 				}
	// 			};

	// 			input.click();
	// 		});

	// 		return view;
	// 	});


	// 	// Definisi schema
	// 	editor.model.schema.register('audio', {
	// 		allowWhere: '$block',
	// 		allowAttributes: ['src'],
	// 		isObject: true,
	// 		isBlock: true
	// 	});

	// 	editor.model.schema.register('image', {
	// 		allowWhere: '$block',
	// 		allowAttributes: ['src'],
	// 		isObject: true,
	// 		isBlock: true
	// 	});


	// 	// Konversi untuk audio
	// 	editor.conversion.for('upcast').elementToElement({
	// 		model: 'audio',
	// 		view: {
	// 			name: 'audio',
	// 			attributes: {
	// 				src: true
	// 			}
	// 		}
	// 	});

	// 	editor.conversion.for('dataDowncast').elementToElement({
	// 		model: 'audio',
	// 		view: (modelElement, { writer }) => {
	// 			const audioElement = writer.createEmptyElement('audio', {
	// 				controls: 'controls',
	// 				src: modelElement.getAttribute('src')
	// 			});

	// 			return audioElement;
	// 		}
	// 	});

	// 	editor.conversion.for('editingDowncast').elementToElement({
	// 		model: 'audio',
	// 		view: (modelElement, { writer }) => {
	// 			const audioElement = writer.createEmptyElement('audio', {
	// 				controls: 'controls',
	// 				src: modelElement.getAttribute('src')
	// 			});

	// 			return audioElement;
	// 		}
	// 	});

		
	// 	// Konversi untuk image
	// 	editor.conversion.for('upcast').elementToElement({
	// 		model: 'image',
	// 		view: {
	// 			name: 'img',
	// 			attributes: {
	// 				src: true
	// 			}
	// 		}
	// 	});

	// 	editor.conversion.for('dataDowncast').elementToElement({
	// 		model: 'image',
	// 		view: (modelElement, { writer }) => {
	// 			const imageElement = writer.createEmptyElement('img', {
	// 				src: modelElement.getAttribute('src')
	// 			});

	// 			return imageElement;
	// 		}
	// 	});

	// 	editor.conversion.for('editingDowncast').elementToElement({
	// 		model: 'image',
	// 		view: (modelElement, { writer }) => {
	// 			const imageElement = writer.createEmptyElement('img', {
	// 				src: modelElement.getAttribute('src')
	// 			});

	// 			return imageElement;
	// 		}
	// 	});
	// }

	function CustomMediaPlugin(editor) {
		// Plugin untuk Image
		editor.ui.componentFactory.add('imageUpload', locale => {
			const view = new ButtonView(locale);
	
			view.set({
				label: 'image',
				withText: true,
				tooltip: 'Upload Image'
			});
	
			view.on('execute', () => {
				const input = document.createElement('input');
				input.type = 'file';
				input.accept = 'image/*';
	
				input.onchange = async () => {
					const file = input.files[0];
					if (file) {
						try {
							const imageUrl = await mediaUpload('IMAGE', file);  // Upload image
							editor.model.change(writer => {
								const imageHtml = `<img src="${imageUrl}" alt="Image" style="width:200px;height:200px;" />`;
								editor.model.insertContent(writer.createRawElement('span', {}, function(domElement) {
									domElement.innerHTML = imageHtml;
								}));
							});
						} catch (error) {
							console.error('Error uploading image:', error);
						}
					}
				};
	
				input.click();
			});
	
			return view;
		});
	
		// Plugin untuk Audio
		editor.ui.componentFactory.add('audioUpload', locale => {
			const view = new ButtonView(locale);
	
			const audioIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-file-earmark-music" viewBox="0 0 16 16">
				<path d="M11 6.64a1 1 0 0 0-1.243-.97l-1 .25A1 1 0 0 0 8 6.89v4.306A2.6 2.6 0 0 0 7 11c-.5 0-.974.134-1.338.377-.36.24-.662.628-.662 1.123s.301.883.662 1.123c.364.243.839.377 1.338.377s.974-.134 1.338-.377c.36-.24.662-.628.662-1.123V8.89l2-.5z"/>
				<path d="M14 14V4.5L9.5 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2M9.5 3A1.5 1.5 0 0 0 11 4.5h2V14a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h5.5z"/>
			</svg>`;
	
			view.set({
				label: '',
				icon: audioIcon,
				withText: false,
				tooltip: 'Upload Audio'
			});
	
			view.on('execute', () => {
				const input = document.createElement('input');
				input.type = 'file';
				input.accept = 'audio/*';
	
				input.onchange = async () => {
					const file = input.files[0];
					if (file) {
						try {
							const audioUrl = await mediaUpload('AUDIO', file);
							
							const audioHtml = `<audio controls src="${audioUrl}"></audio>`;
							
							const viewFragment = editor.data.processor.toView(audioHtml);
							const modelFragment = editor.data.toModel(viewFragment);
							
							editor.model.insertContent(modelFragment, editor.model.document.selection);
						} catch (error) {
							console.error('Error uploading audio:', error);
						}
					}
				};
	
				input.click();
			});
	
			return view;
		});
	
		// Konversi Audio sebagai elemen HTML biasa


	}
	

    const fetchData = async () => {
        setLoading(true);
        try {
            const data = await materialService.getLevelById(materialId);
            // console.log(data.payload);
            setEditorData(data.payload.CONTENT);
            setLevelName(data.payload.NAME_LEVEL);
            setSectionName(data.payload.NAME_SECTION);
            setTopicName(data.payload.NAME_TOPIC);
            setLoading(false);
        } catch (error) {
            setError(error);
        }
    };

	useEffect(() => {
        fetchData();
		setIsLayoutReady(true);
		return () => setIsLayoutReady(false);
	}, [materialId]);

    const handleSubmit = async () => {
        if (!editorData) {
            alert('Content is empty');
            return;
        }

        const updateData = new FormData();
        updateData.append('CONTENT', editorData);

        handleShowLoader('Updated', '', true);
        try {
            const update = await materialService.updateData(materialId, updateData);
            setEditorData(update.payload.CONTENT);
            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
            }));
        }
    };

    return {
		loading,
		error,
        show,
        editorData,
        levelName,
        sectionName,
        topicName,
        handleEditorChange,
        editorContainerRef,
        editorRef,
        isLayoutReady,
        mediaUpload,
        MyUploadAdapter,
        CustomUploadAdapterPlugin,
        CustomMediaPlugin,

        handleSubmit,

		showLoader,
		handleCloseLoader,
		loaderState,
    };
};

export default useTest;

