import sanitizeHtml from 'sanitize-html';
import { __ } from '@wordpress/i18n';

export const openMediaUploader = ( type, callback ) => {
	let mediaUploader;

	const mediaUploaderData = ( fileType ) => {
		switch ( fileType ) {
			case 'image':
				return {
					title: __( 'Choose Image', 'easy-content-manager' ),
					button: {
						text: __( 'Choose Image', 'easy-content-manager' ),
					},
					multiple: false,
				};
			case 'pdf':
				return {
					title: __( 'Choose PDF', 'easy-content-manager' ),
					button: {
						text: __( 'Choose PDF', 'easy-content-manager' ),
					},
					multiple: false,
				};
			case 'audio':
				return {
					title: __( 'Choose Audio', 'easy-content-manager' ),
					button: {
						text: __( 'Choose Audio', 'easy-content-manager' ),
					},
					multiple: false,
				};
			case 'video':
				return {
					title: __( 'Choose Video', 'easy-content-manager' ),
					button: {
						text: __( 'Choose Video', 'easy-content-manager' ),
					},
					multiple: false,
				};
			default:
				return {
					title: __( 'Choose Image', 'easy-content-manager' ),
					button: {
						text: __( 'Choose Image', 'easy-content-manager' ),
					},
					multiple: false,
				};
		}
	};

	mediaUploader = window.wp.media( mediaUploaderData( type ) );

	mediaUploader.on( 'select', function () {
		const attachment = mediaUploader
			.state()
			.get( 'selection' )
			.first()
			.toJSON();
		callback( attachment );
	} );

	mediaUploader.open();
};

export const generateMediaContent = ( attachment, type ) => {
	switch ( type ) {
		case 'image':
			return `<img src="${ attachment.url }" alt="${
				attachment.alt || ''
			}" style="max-width: 100%"/>`;
		case 'video':
			return `<video src="${ attachment.url }" type="${
				attachment.mime || 'video/mp4'
			}" controls><source>${ __(
				'Your browser does not support the video tag.',
				'easy-content-manager'
			) }</video>`;
		case 'pdf':
			return `
        <div style="display: inline-block; margin: 10px 0;">
            <a href="${
				attachment.url
			}" target="_blank" rel="noopener noreferrer" style="display: inline-flex;">
                <span>${
					attachment.filename || attachment.title || 'PDF Document'
				}</span>
            </a>
        </div>`;
		case 'audio':
			return `<audio controls><source src="${ attachment.url }" type="${
				attachment.mime || 'audio/mpeg'
			}">${ __(
				'Your browser does not support the audio tag.',
				'easy-content-manager'
			) }</audio>`;
		default:
			return '';
	}
};

export function insertTableHandel( insertContentAtCursor, __ ) {
	try {
		const rows = prompt(
			__( 'How many rows do you want?', 'easy-content-manager' ),
			'3'
		);
		if ( ! rows || isNaN( rows ) || parseInt( rows ) < 1 ) {
			alert(
				__(
					'Please enter a valid number of rows (minimum 1)',
					'easy-content-manager'
				)
			);
			return;
		}

		const columns = prompt(
			__( 'How many columns do you want?', 'easy-content-manager' ),
			'3'
		);
		if ( ! columns || isNaN( columns ) || parseInt( columns ) < 1 ) {
			alert(
				__(
					'Please enter a valid number of columns (minimum 1)',
					'easy-content-manager'
				)
			);
			return;
		}

		const numRows = parseInt( rows );
		const numColumns = parseInt( columns );

		let tableHtml = `<table border="1" cellpadding="5" cellspacing="0" style="border-collapse: collapse; width: 100%; margin: 10px 0;">
			<thead>
				<tr style="background-color: #f5f5f5;">`;

		for ( let col = 1; col <= numColumns; col++ ) {
			tableHtml += `<th style="border: 1px solid #ddd; padding: 8px; text-align: left;">${ __(
				'Header',
				'easy-content-manager'
			) } ${ col }</th>`;
		}

		tableHtml += `</tr>
			</thead>
			<tbody>`;

		for ( let row = 1; row <= numRows; row++ ) {
			tableHtml += `<tr>`;
			for ( let col = 1; col <= numColumns; col++ ) {
				tableHtml += `<td style="border: 1px solid #ddd; padding: 8px;">${ __(
					'Row',
					'easy-content-manager'
				) } ${ row }, ${ __(
					'Col',
					'easy-content-manager'
				) } ${ col }</td>`;
			}
			tableHtml += `</tr>`;
		}

		tableHtml += `</tbody></table>`;

		insertContentAtCursor( tableHtml );
	} catch ( error ) {
		console.error( 'Error inserting table:', error );
	}
}

const sanitizeOptions = {
	allowedTags: [
		'p',
		'br',
		'strong',
		'b',
		'em',
		'i',
		'u',
		'strike',
		's',
		'del',
		'ul',
		'ol',
		'li',
		'a',
		'img',
		'video',
		'source',
		'table',
		'thead',
		'tbody',
		'tr',
		'th',
		'td',
		'div',
		'span',
		'blockquote',
		'font',
		'svg',
		'path',
	],
	allowedAttributes: {
		'*': [ 'style', 'class' ],
		a: [ 'href', 'target', 'rel' ],
		img: [ 'src', 'alt', 'width', 'height' ],
		video: [ 'controls', 'src', 'width', 'height' ],
		audio: [ 'controls', 'width', 'height', 'src', 'class' ],
		source: [ 'src', 'type' ],
		table: [ 'border', 'cellpadding', 'cellspacing' ],
		ul: [ 'type' ],
		ol: [ 'type', 'start' ],
		font: [ 'color' ],
		span: [ 'style', 'class' ],
		div: [ 'class' ],
		svg: [ 'width', 'height', 'viewBox', 'fill', 'xmlns' ],
		path: [ 'd', 'fill', 'stroke', 'stroke-width' ],
	},
	allowedStyles: {
		'*': {
			margin: [ /^[\d\s.px%em-]+$/ ],
			padding: [ /^[\d\s.px%em-]+$/ ],
			'font-weight': [ /^(?:normal|bold|bolder|lighter|\d{3})$/ ],
			'list-style': [
				/^(?:disc|circle|square|decimal|lower-alpha|upper-alpha|lower-roman|upper-roman|none)$/,
			],
			'list-style-type': [
				/^(?:disc|circle|square|decimal|lower-alpha|upper-alpha|lower-roman|upper-roman|none)$/,
			],
			'text-decoration': [ /^(?:none|underline|line-through|overline)$/ ],
			color: [
				/^#[0-9a-f]{3,8}$/i,
				/^rgb\([0-9, ]+\)$/,
				/^rgba\([0-9, .]+\)$/,
				/^[a-z]+$/i,
				/^transparent$/i,
			],
			'background-color': [
				/^#[0-9a-f]{3,8}$/i,
				/^rgb\([0-9, ]+\)$/,
				/^rgba\([0-9, .]+\)$/,
				/^[a-z]+$/i,
				/^transparent$/i,
			],
			'text-align': [ /^(?:left|center|right|justify)$/ ],
			display: [
				/^(?:block|inline|inline-block|none|flex|inline-flex)$/,
			],
			'align-items': [
				/^(?:center|flex-start|flex-end|stretch|baseline)$/,
			],
			gap: [ /^[\d.]+(?:px|em|rem)$/ ],
			border: [
				/^(?:none|\d+px\s+solid\s+#[0-9a-f]{3,6}|\d+px\s+solid\s+[a-z]+)$/i,
			],
			'border-radius': [ /^\d+px$/ ],
		},
		p: {
			'text-align': [ /^(?:left|center|right|justify)$/ ],
			color: [
				/^#[0-9a-f]{3,8}$/i,
				/^rgb\([0-9, ]+\)$/,
				/^rgba\([0-9, .]+\)$/,
				/^[a-z]+$/i,
				/^transparent$/i,
			],
			'background-color': [
				/^#[0-9a-f]{3,8}$/i,
				/^rgb\([0-9, ]+\)$/,
				/^rgba\([0-9, .]+\)$/,
				/^[a-z]+$/i,
				/^transparent$/i,
			],
		},
		div: {
			'text-align': [ /^(?:left|center|right|justify)$/ ],
			color: [
				/^#[0-9a-f]{3,8}$/i,
				/^rgb\([0-9, ]+\)$/,
				/^rgba\([0-9, .]+\)$/,
				/^[a-z]+$/i,
				/^transparent$/i,
			],
			'background-color': [
				/^#[0-9a-f]{3,8}$/i,
				/^rgb\([0-9, ]+\)$/,
				/^rgba\([0-9, .]+\)$/,
				/^[a-z]+$/i,
				/^transparent$/i,
			],
			display: [
				/^(?:block|inline|inline-block|none|flex|inline-flex)$/,
			],
			'align-items': [
				/^(?:center|flex-start|flex-end|stretch|baseline)$/,
			],
			gap: [ /^[\d.]+(?:px|em|rem)$/ ],
			border: [
				/^(?:none|\d+px\s+solid\s+#[0-9a-f]{3,6}|\d+px\s+solid\s+[a-z]+)$/i,
			],
			'border-radius': [ /^\d+px$/ ],
			margin: [ /^[\d\s.px%em-]+$/ ],
			padding: [ /^[\d\s.px%em-]+$/ ],
		},
		a: {
			display: [
				/^(?:block|inline|inline-block|none|flex|inline-flex)$/,
			],
			'align-items': [
				/^(?:center|flex-start|flex-end|stretch|baseline)$/,
			],
			gap: [ /^[\d.]+(?:px|em|rem)$/ ],
			padding: [ /^[\d\s.px%em-]+$/ ],
			border: [
				/^(?:none|\d+px\s+solid\s+#[0-9a-f]{3,6}|\d+px\s+solid\s+[a-z]+)$/i,
			],
			'border-radius': [ /^\d+px$/ ],
			'text-decoration': [ /^(?:none|underline|line-through|overline)$/ ],
			color: [
				/^#[0-9a-f]{3,8}$/i,
				/^rgb\([0-9, ]+\)$/,
				/^rgba\([0-9, .]+\)$/,
				/^[a-z]+$/i,
				/^transparent$/i,
			],
		},
		span: {
			color: [
				/^#[0-9a-f]{3,8}$/i,
				/^rgb\([0-9, ]+\)$/,
				/^rgba\([0-9, .]+\)$/,
				/^[a-z]+$/i,
				/^transparent$/i,
			],
			'background-color': [
				/^#[0-9a-f]{3,8}$/i,
				/^rgb\([0-9, ]+\)$/,
				/^rgba\([0-9, .]+\)$/,
				/^[a-z]+$/i,
				/^transparent$/i,
			],
		},
		img: {
			width: [ /^[\d.]+(?:px|%|em|rem)$/ ],
			height: [ /^[\d.]+(?:px|%|em|rem|auto)$/ ],
			float: [ /^(?:left|right|none)$/ ],
			display: [ /^(?:block|inline|inline-block|none)$/ ],
			margin: [ /^[\d\s.px%em-]+$/ ],
			'margin-left': [ /^[\d.-]+(?:px|em|rem|%|auto)$/ ],
			'margin-right': [ /^[\d.-]+(?:px|em|rem|%|auto)$/ ],
			'margin-top': [ /^[\d.-]+(?:px|em|rem|%)$/ ],
			'margin-bottom': [ /^[\d.-]+(?:px|em|rem|%)$/ ],
			border: [ /^(?:none|\d+px\s+solid\s+#[0-9a-f]{3,6})$/i ],
			'border-radius': [ /^\d+px$/ ],
			'max-width': [ /^[\d.]+(?:px|%|em|rem)$/ ],
			'text-align': [ /^(?:left|center|right|justify)$/ ],
		},
		video: {
			width: [ /^[\d.]+(?:px|%|em|rem)$/ ],
			height: [ /^[\d.]+(?:px|%|em|rem|auto)$/ ],
			float: [ /^(?:left|right|none)$/ ],
			display: [ /^(?:block|inline|inline-block|none)$/ ],
			margin: [ /^[\d\s.px%em-]+$/ ],
			'margin-left': [ /^[\d.-]+(?:px|em|rem|%|auto)$/ ],
			'margin-right': [ /^[\d.-]+(?:px|em|rem|%|auto)$/ ],
			'margin-top': [ /^[\d.-]+(?:px|em|rem|%)$/ ],
			'margin-bottom': [ /^[\d.-]+(?:px|em|rem|%)$/ ],
			border: [ /^(?:none|\d+px\s+solid\s+#[0-9a-f]{3,6})$/i ],
			'border-radius': [ /^\d+px$/ ],
			'max-width': [ /^[\d.]+(?:px|%|em|rem)$/ ],
			'text-align': [ /^(?:left|center|right|justify)$/ ],
		},
		ul: {
			margin: [ /^[\d\s.px%em-]+$/ ],
			'margin-left': [ /^[\d.-]+(?:px|em|rem|%|auto)$/ ],
			'margin-right': [ /^[\d.-]+(?:px|em|rem|%|auto)$/ ],
			'margin-top': [ /^[\d.-]+(?:px|em|rem|%)$/ ],
			'margin-bottom': [ /^[\d.-]+(?:px|em|rem|%)$/ ],
			padding: [ /^[\d\s.px%em-]+$/ ],
			'padding-left': [ /^[\d.-]+(?:px|em|rem|%|auto)$/ ],
			'padding-right': [ /^[\d.-]+(?:px|em|rem|%|auto)$/ ],
			'padding-top': [ /^[\d.-]+(?:px|em|rem|%)$/ ],
			'padding-bottom': [ /^[\d.-]+(?:px|em|rem|%)$/ ],
			'list-style-type': [
				/^(?:disc|circle|square|decimal|lower-alpha|upper-alpha|lower-roman|upper-roman|none)$/,
			],
		},
		ol: {
			margin: [ /^[\d\s.px%em-]+$/ ],
			'margin-left': [ /^[\d.-]+(?:px|em|rem|%|auto)$/ ],
			'margin-right': [ /^[\d.-]+(?:px|em|rem|%|auto)$/ ],
			'margin-top': [ /^[\d.-]+(?:px|em|rem|%)$/ ],
			'margin-bottom': [ /^[\d.-]+(?:px|em|rem|%)$/ ],
			padding: [ /^[\d\s.px%em-]+$/ ],
			'padding-left': [ /^[\d.-]+(?:px|em|rem|%|auto)$/ ],
			'padding-right': [ /^[\d.-]+(?:px|em|rem|%|auto)$/ ],
			'padding-top': [ /^[\d.-]+(?:px|em|rem|%)$/ ],
			'padding-bottom': [ /^[\d.-]+(?:px|em|rem|%)$/ ],
			'list-style-type': [
				/^(?:disc|circle|square|decimal|lower-alpha|upper-alpha|lower-roman|upper-roman|none)$/,
			],
		},
		li: {
			margin: [ /^[\d\s.px%em-]+$/ ],
			'margin-left': [ /^[\d.-]+(?:px|em|rem|%|auto)$/ ],
			'margin-right': [ /^[\d.-]+(?:px|em|rem|%|auto)$/ ],
			'margin-top': [ /^[\d.-]+(?:px|em|rem|%)$/ ],
			'margin-bottom': [ /^[\d.-]+(?:px|em|rem|%)$/ ],
			padding: [ /^[\d\s.px%em-]+$/ ],
			'padding-left': [ /^[\d.-]+(?:px|em|rem|%|auto)$/ ],
			'padding-right': [ /^[\d.-]+(?:px|em|rem|%|auto)$/ ],
			'padding-top': [ /^[\d.-]+(?:px|em|rem|%)$/ ],
			'padding-bottom': [ /^[\d.-]+(?:px|em|rem|%)$/ ],
		},
	},
	transformTags: {
		strike: 's',
		del: 's',
		video( tagName, attribs ) {
			if ( ! attribs.style ) {
				attribs.style = 'max-width:100%;';
			} else if ( ! /max-width\s*:\s*/i.test( attribs.style ) ) {
				attribs.style += ' max-width:100%;';
			}
			return { tagName, attribs };
		},
	},
};

export const sanitizeContent = ( html ) => {
	let cleanedHtml = html;

	cleanedHtml = cleanedHtml.replace( /<ul\s+id="[^"]*"/g, '<ul' );
	cleanedHtml = cleanedHtml.replace( /<ol\s+id="[^"]*"/g, '<ol' );
	cleanedHtml = cleanedHtml.replace( /data-list-text="[^"]*"/g, '' );

	cleanedHtml = cleanedHtml.replace( /<\!DOCTYPE[^>]*>/gi, '' );
	cleanedHtml = cleanedHtml.replace( /<html[^>]*>/gi, '' );
	cleanedHtml = cleanedHtml.replace( /<\/html>/gi, '' );
	cleanedHtml = cleanedHtml.replace( /<head[^>]*>[\s\S]*?<\/head>/gi, '' );
	cleanedHtml = cleanedHtml.replace( /<body[^>]*>/gi, '' );
	cleanedHtml = cleanedHtml.replace( /<\/body>/gi, '' );

	cleanedHtml = cleanedHtml.replace( /<h[1-6]([^>]*)>/gi, '<p$1>' );
	cleanedHtml = cleanedHtml.replace( /<\/h[1-6]>/gi, '</p>' );

	cleanedHtml = cleanedHtml.replace( /font-size\s*:\s*[^;]*;?/gi, '' );

	cleanedHtml = cleanedHtml.replace( /style\s*=\s*["'][;:\s]*["']/gi, '' );

	const sanitized = sanitizeHtml( cleanedHtml, sanitizeOptions );

	const tempDiv = document.createElement( 'div' );
	tempDiv.innerHTML = sanitized;

	const allElements = tempDiv.querySelectorAll( '*' );
	allElements.forEach( ( element ) => {
		if ( element.style && element.style.fontSize ) {
			element.style.removeProperty( 'font-size' );
		}

		if ( element.hasAttribute( 'style' ) ) {
			const styleText = element.style.cssText.trim();
			if ( styleText === '' || styleText === ';' ) {
				element.removeAttribute( 'style' );
			}
		}
	} );

	const ulElements = tempDiv.querySelectorAll( 'ul' );
	const olElements = tempDiv.querySelectorAll( 'ol' );

	ulElements.forEach( ( ul ) => {
		if ( ! ul.style.listStyleType ) {
			ul.style.listStyleType = 'disc';
		}
		if ( ! ul.style.marginLeft && ! ul.style.margin ) {
			ul.style.marginLeft = '20px';
		}
		if ( ! ul.style.paddingLeft && ! ul.style.padding ) {
			ul.style.paddingLeft = '20px';
		}
	} );

	olElements.forEach( ( ol ) => {
		if ( ! ol.style.listStyleType ) {
			ol.style.listStyleType = 'decimal';
		}
		if ( ! ol.style.marginLeft && ! ol.style.margin ) {
			ol.style.marginLeft = '20px';
		}
		if ( ! ol.style.paddingLeft && ! ol.style.padding ) {
			ol.style.paddingLeft = '20px';
		}
	} );

	return tempDiv.innerHTML;
};

export const widthsList = [
	{ value: 'auto', label: 'auto' },
	{ value: '25%', label: '25%' },
	{ value: '50%', label: '50%' },
	{ value: '75%', label: '75%' },
	{ value: '100%', label: '100%' },
];

export const alignmentList = [
	{
		label: (
			<span>
				<svg
					width="16"
					height="16"
					viewBox="0 0 24 24"
					fill="currentColor"
				>
					<path d="M3 21h18v-2H3v2zm0-4h12v-2H3v2zm0-4h18v-2H3v2zm0-4h12V7H3v2zm0-6v2h18V3H3z" />
				</svg>
				{ __( '- Left', 'easy-content-manager' ) }
			</span>
		),
		value: 'left',
	},
	{
		label: (
			<span>
				<svg
					width="16"
					height="16"
					viewBox="0 0 24 24"
					fill="currentColor"
				>
					<path d="M7 15v2h10v-2H7zm-4 6h18v-2H3v2zm0-8h18v-2H3v2zm4-6v2h10V7H7zM3 3v2h18V3H3z" />
				</svg>
				{ __( '- Center', 'easy-content-manager' ) }
			</span>
		),
		value: 'center',
	},
	{
		label: (
			<span>
				<svg
					width="16"
					height="16"
					viewBox="0 0 24 24"
					fill="currentColor"
				>
					<path d="M3 21h18v-2H3v2zm6-4h12v-2H9v2zm-6-4h18v-2H3v2zm6-4h12V7H9v2zm-6-6v2h18V3H3z" />
				</svg>
				{ __( '- Right', 'easy-content-manager' ) }
			</span>
		),
		value: 'right',
	},
];
