import React, { useCallback } from 'react';
import type { PostPdfGlobal } from '@/editor/posts-to-pdf/generatePdfFromPost';
import { usePdfFromPost } from '@/editor/posts-to-pdf/usePdfFromPost';

interface DownloadButtonProps {
	postId: number;
	buttonText: string;
	className: string;
	config?: PostPdfGlobal;
}

function Spinner() {
	const ref = React.useRef<HTMLSpanElement>(null);

	React.useEffect(() => {
		if (!ref.current) return;
		// Web Animations API keeps the animation on the compositor thread
		// explicitly, so it continues smoothly even when the main thread is
		// saturated by html2canvas / jsPDF work.
		const anim = ref.current.animate(
			[{ transform: 'rotate(0deg)' }, { transform: 'rotate(360deg)' }],
			{ duration: 800, iterations: Infinity, easing: 'linear' },
		);
		return () => anim.cancel();
	}, []);

	return (
		<span
			ref={ref}
			aria-hidden="true"
			style={{
				width: '14px',
				height: '14px',
				border: '2px solid currentColor',
				borderTopColor: 'transparent',
				borderRadius: '9999px',
				display: 'inline-block',
				willChange: 'transform',
			}}
		/>
	);
}

const DEFAULT_BUTTON_STYLES = `
.pdfdraft-download-btn{
	display:inline-flex;
	align-items:center;
	gap:.45em;
	padding:16px 20px;
	font-size:14px;
	font-weight:500;
	line-height:1;
	color:var(--wp--preset--color--base, #fff);
	background:var(--wp--preset--color--primary, var(--wp-admin-theme-color, #2271b1));
	border:1px solid var(--wp--preset--color--primary, var(--wp-admin-theme-color, #2271b1));
	border-radius:7px;
	cursor:pointer;
	transition:background .15s ease,transform .15s ease,box-shadow .15s ease;
	text-decoration:none;
	font-family:inherit;
}
.pdfdraft-download-btn:hover:not(:disabled){
	background:var(--wp--preset--color--primary, var(--wp-admin-theme-color, #2271b1));
	box-shadow:0 2px 6px rgba(0,0,0,.15);
}
.pdfdraft-download-btn:active:not(:disabled){
	transform:translateY(1px);
}
.pdfdraft-download-btn:disabled{
	opacity:1;
	cursor:wait;
}
@keyframes pdfdraft-spin{to{transform:rotate(360deg)}}
`;

export function DownloadButton({ postId, buttonText, className, config }: DownloadButtonProps) {
	const { isLoading, error, generatePdf } = usePdfFromPost();
	const hasCustomClass = Boolean(className && className.trim());
	const usesThemeButton = /\b(wp-block-button__link|wp-element-button)\b/.test(className);

	const handleClick = useCallback(
		(e: React.MouseEvent<HTMLButtonElement>) => {
			e.preventDefault();
			if (config) {
				void generatePdf(postId, config);
				return;
			}
			void generatePdf(postId);
		},
		[config, generatePdf, postId],
	);

	const finalClassName = hasCustomClass
		? `pdfdraft-download-btn ${className}`
		: 'pdfdraft-download-btn';

	return (
		<>
			{!usesThemeButton && <style>{DEFAULT_BUTTON_STYLES}</style>}
			<button
				type="button"
				className={finalClassName}
				onClick={handleClick}
				disabled={isLoading}
				aria-busy={isLoading}
			>
				<span>{buttonText}</span>
				{isLoading && <Spinner />}
			</button>
			{error && (
				<p
					style={{
						color: '#dc2626',
						fontSize: '13px',
						marginTop: '6px',
						marginBottom: 0,
						background: '#fef2f2',
						border: '1px solid #fecaca',
						borderRadius: '4px',
						padding: '6px 10px',
						maxWidth: '320px',
					}}
				>
					{error}
				</p>
			)}
		</>
	);
}
