import React from 'react';
import { Row, Col, Button, Form, Modal, InputGroup, Breadcrumb, Spinner } from 'react-bootstrap';
import { CKEditor } from '@ckeditor/ckeditor5-react';
import {
	ClassicEditor,
	Base64UploadAdapter,
	SimpleUploadAdapter,
	GeneralHtmlSupport,
	AccessibilityHelp, Alignment, Autoformat, AutoImage, AutoLink, Autosave, BlockQuote, Bold, Essentials, FindAndReplace,FontBackgroundColor, FontColor, FontFamily, FontSize, 
	Heading, Highlight, HorizontalLine, ImageBlock, ImageCaption, ImageInline, ImageInsert, ImageInsertViaUrl, ImageResize, ImageStyle, ImageTextAlternative, ImageToolbar, ImageUpload, Indent, IndentBlock, Italic,
	Link, LinkImage, List, ListProperties, MediaEmbed, Paragraph, PasteFromOffice, RemoveFormat, SelectAll, SpecialCharacters, SpecialCharactersArrows, SpecialCharactersCurrency, SpecialCharactersEssentials, SpecialCharactersLatin, SpecialCharactersMathematical, SpecialCharactersText, Strikethrough, Subscript, Superscript,
	Table, TableCaption, TableCellProperties, TableColumnResize, TableProperties, TableToolbar, TextTransformation, TodoList, Underline, Undo,
	ButtonView
} from 'ckeditor5';
import 'ckeditor5/ckeditor5.css';
import useEditorMaterial from '../hooks/useEditorMaterial';
import { useParams } from 'react-router-dom';
import { Link as BtnLink } from 'react-router-dom';
import ModalOperation from '../../../../components/ui/adminMessageModal/ModalOperation';

const EditorMaterial = () => {
    const { materialId } = useParams();
	const {
		loading,
		error,
        show,
        editorData,
        levelName,
        sectionName,
        topicName,
        handleEditorChange,
		editorContainerRef,
        editorRef,
        isLayoutReady,
        CustomUploadAdapterPlugin,
        CustomMediaPlugin,
		handleSubmit,
		showLoader,
		loaderState,
		handleCloseLoader,
	} = useEditorMaterial(materialId);

	const editorConfig = {
		toolbar: {
			items: [
				'findAndReplace','undo', 'redo', '|', 'heading', 'fontFamily', 'fontSize', '|', 'bold', 'italic', 'underline', 'fontColor', 'fontBackgroundColor', '|', 
				'link', 
				'imageUpload',
				'audioUpload',
				'mediaEmbed',
				'|', 'alignment', 'numberedList', 'bulletedList', 'todoList', 'outdent', 'indent', '|',
				'removeFormat', '|',
				// 'insertImage',
				// 'insertImageViaUrl',
			],
			shouldNotGroupWhenFull: true
		},
		plugins: [
			CustomMediaPlugin,
			// Base64UploadAdapter,
			// SimpleUploadAdapter,
			GeneralHtmlSupport,
			AccessibilityHelp, Alignment, Autoformat, AutoImage, AutoLink, Autosave, BlockQuote, Bold, Essentials, FindAndReplace, FontBackgroundColor, FontColor, FontFamily, FontSize, 
			Heading, Highlight, HorizontalLine, ImageBlock, ImageCaption, ImageInline, ImageInsert, ImageResize, ImageStyle, ImageTextAlternative, ImageToolbar, ImageUpload, Indent, IndentBlock, Italic,
			Link, LinkImage, List, ListProperties, MediaEmbed, Paragraph, PasteFromOffice, RemoveFormat, SelectAll, SpecialCharacters, SpecialCharactersArrows, SpecialCharactersCurrency, SpecialCharactersEssentials, SpecialCharactersLatin, SpecialCharactersMathematical, SpecialCharactersText, Strikethrough, Subscript, Superscript,
			Table, TableCaption, TableCellProperties, TableColumnResize, TableProperties, TableToolbar, TextTransformation, TodoList, Underline, Undo
		],
		htmlSupport: {
			allow: [
				{
					name: 'audio',
					attributes: true,
					classes: true,
					styles: true
				}
			]
		},		
		extraPlugins: [CustomUploadAdapterPlugin],
		removePlugins: ['ImageInsert'],
		fontFamily: {
			supportAllValues: true
		},
		fontSize: {
			options: [10, 12, 14, 'default', 18, 20, 22],
			supportAllValues: true
		},
		heading: {
			options: [
				{
					model: 'paragraph',
					title: 'Paragraph',
					class: 'ck-heading_paragraph'
				},
				{
					model: 'heading1',
					view: 'h1',
					title: 'Heading 1',
					class: 'ck-heading_heading1'
				},
				{
					model: 'heading2',
					view: 'h2',
					title: 'Heading 2',
					class: 'ck-heading_heading2'
				},
				{
					model: 'heading3',
					view: 'h3',
					title: 'Heading 3',
					class: 'ck-heading_heading3'
				},
				{
					model: 'heading4',
					view: 'h4',
					title: 'Heading 4',
					class: 'ck-heading_heading4'
				},
				{
					model: 'heading5',
					view: 'h5',
					title: 'Heading 5',
					class: 'ck-heading_heading5'
				},
				{
					model: 'heading6',
					view: 'h6',
					title: 'Heading 6',
					class: 'ck-heading_heading6'
				}
			]
		},
		image: {
			toolbar: [
				'toggleImageCaption',
				'imageTextAlternative',
				'|',
				'imageStyle:inline',
				'imageStyle:wrapText',
				'imageStyle:breakText',
				'|',
				'resizeImage'
			]
		},
        mediaEmbed: {
            providers: [
                {
                    name: 'youtube',
                    url: [
                        /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/
                    ],
                    html: match => {
                        const id = match[0].includes('watch?v=')
                        ? match[0].split('watch?v=')[1]
                        : match[0].split('youtu.be/')[1];
                        const embedUrl = `https://www.youtube.com/embed/${id}`;
                        return `<iframe controls src="${embedUrl}" style="aspect-ratio:3/2;width:40vw;height:auto"></iframe>`;
                    }
                },
                {
                    name: 'googleDrive',
                    url: [
                        /https?:\/\/drive\.google\.com\/file\/d\/([a-zA-Z0-9_-]+)\/(?:view|preview)/
                    ],
                    html: match => {
                        const id = match[0].split('/d/')[1].split('/')[0];
                        // const embedUrl = `https://drive.google.com/uc?export=download&id=${id}`;
                        const embedUrl = `https://drive.google.com/file/d/${id}/preview`;
                        return `<iframe controls src="${embedUrl}" style="aspect-ratio:3/2;width:40vw;height:auto"></iframe>`;
                    }
                }
            ]
        },
		initialData:
			editorData,
		link: {
			addTargetToExternalLinks: true,
			defaultProtocol: 'https://',
			decorators: {
				toggleDownloadable: {
					mode: 'manual',
					label: 'Downloadable',
					attributes: {
						download: 'file'
					}
				}
			}
		},
		list: {
			properties: {
				styles: true,
				startIndex: true,
				reversed: true
			}
		},
		menuBar: {
			isVisible: true
		},
		placeholder: 'Type or paste the material here!',
		table: {
			contentToolbar: ['tableColumn', 'tableRow', 'mergeTableCells', 'tableProperties', 'tableCellProperties']
		}
	};

	return (
		<div>
            <Row className='mb-45'>
                <Col className="d-flex align-items-center breadcrumb-con">
                    <Button as={BtnLink} className='btn btn-blue btn-square-back' to='/admin/material'>
                        <i className="bi bi-arrow-90deg-left"></i>
                    </Button>
                    <Breadcrumb className='custom-breadcrumb'>
                        <Breadcrumb.Item href="#">Learning</Breadcrumb.Item>
                        <Breadcrumb.Item href="/admin/material" className='text-capitalize'>Materials</Breadcrumb.Item>
                        <Breadcrumb.Item active>Update Materials</Breadcrumb.Item>
                    </Breadcrumb>
                </Col>
            </Row>
            <Row className='mb-45'>
                <Col>
                    <div className="cards">
                        <div className="cards-title d-flex">
                            <h4>{sectionName} : {topicName} - <span className='text-blue'>{levelName}</span></h4>
                        </div>
                        <div className="cards-body">
                            <label className='mb-2 fw-500'>Material Content <sup className='text-red fw-bold'>*</sup></label>
                            <div className="mb-4 main-container">
                                <div className="editor-container editor-container_classic-editor" ref={editorContainerRef}>
                                    <div className="editor-container__editor">
                                        <div ref={editorRef}>
                                            {isLayoutReady && 
                                                <CKEditor 
                                                    editor={ClassicEditor} 
                                                    config={editorConfig} 
                                                    data={editorData || ""}
                                                    onChange={handleEditorChange}
                                                />
                                            }
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div className="d-flex justify-content-end">
                                <Button variant="blue" onClick={handleSubmit} className='ms-2 py-2 px-5 rounded-35'>
                                    Save
                                </Button>
                            </div>
                        </div>
                    </div>
                </Col>
            </Row>

            <Modal show={show} centered>
                <Modal.Body>
                    <div className='w-100 d-flex justify-content-center align-items-center' style={{height:"20vh"}}>
                        <Spinner animation="grow" variant="primary" />
                        <Spinner animation="grow" variant="secondary" />
                        <Spinner animation="grow" variant="success" />
                        <Spinner animation="grow" variant="danger" />
                        <Spinner animation="grow" variant="warning" />
                        <Spinner animation="grow" variant="info" />
                    </div>
                </Modal.Body>
            </Modal>

			<ModalOperation
				show={showLoader}
				handleClose={handleCloseLoader}
				title={loaderState.title}
				description={loaderState.description}
				loading={loaderState.loading}
				successMessage={loaderState.successMessage}
				confirmAction={loaderState.confirmAction}
				handleConfirm={loaderState.handleConfirm}
			/>
		</div>
	);
};

export default EditorMaterial;
