/** @jsxRuntime classic */

type EmbedDefaults = {
	width?: string;
	height?: string;
};

type BlockAttrs = {
	templateId?: string;
	orderId?: string;
	width?: string;
	height?: string;
};

const localized = ((window as any).__PDFDRAFT_EMBED_PDF__ ?? {}) as {
	defaults?: EmbedDefaults;
};
const wpAny = (window as any).wp;
const React = wpAny?.element;
const { InspectorControls, useBlockProps } = wpAny?.blockEditor ?? {};
const { PanelBody, SelectControl, Button, TextControl } = wpAny?.components ?? {};
const { __ } = wpAny?.i18n ?? { __: (v: string) => v };
const apiFetch = wpAny?.apiFetch as
	| ((args: Record<string, any>) => Promise<any>)
	| undefined;

const defaultWidth = localized.defaults?.width || '100%';
const defaultHeight = localized.defaults?.height || '840px';

const PdfDraftIcon = () =>
	React.createElement(
		'svg',
		{
			width: 20,
			height: 22,
			viewBox: '0 0 40 40',
			fill: 'none',
			xmlns: 'http://www.w3.org/2000/svg',
		},
		React.createElement('path', {
			d: 'M22.5 11.797c0 .902.844 1.64 1.875 1.64H35V35.86c0 .909-.836 1.64-1.875 1.64h-21.38l3.55-5.786q.12-.214.358-.315a.87.87 0 0 1 .511-.048 7.3 7.3 0 0 0 3.435-.22 7.1 7.1 0 0 0 2.954-1.749 6.8 6.8 0 0 0 1.755-2.876 6.4 6.4 0 0 0 .142-3.322 1 1 0 0 0-.443-.676 1.14 1.14 0 0 0-.778-.176q-.423.051-.732.404l-2.627 3.898q-.379.504-1.05.571a1.65 1.65 0 0 1-1.198-.325l-2.593-1.943a1.53 1.53 0 0 1-.622-1.026q-.098-.63.334-1.17.434-.54 1.614-1.7 1.18-1.161 1.642-1.704.276-.378.208-.784a1.13 1.13 0 0 0-.386-.683q-.317-.275-.787-.246-1.56.076-2.947.775a6.8 6.8 0 0 0-2.327 1.902 6.7 6.7 0 0 0-1.426 3.465 6.7 6.7 0 0 0 .61 3.645.95.95 0 0 1 .05.495.7.7 0 0 1-.227.413L5 33.911V4.141C5 3.23 5.836 2.5 6.875 2.5H22.5z',
			fill: '#E50001',
		}),
		React.createElement('path', {
			d: 'M25.477 2.5c.5 0 .976.17 1.328.478l7.648 6.7c.352.307.547.725.547 1.155v.63H24.416V2.5z',
			fill: '#E50001',
		}),
	);

export default function Edit({
	attributes,
	setAttributes,
}: {
	attributes: BlockAttrs;
	setAttributes: (next: Partial<BlockAttrs>) => void;
}) {
	if (
		!React ||
		!InspectorControls ||
		!useBlockProps ||
		!PanelBody ||
		!SelectControl ||
		!Button ||
		!TextControl ||
		!apiFetch
	) {
		return null;
	}

	const normalizeDimension = (value: string | undefined, fallback: string): string => {
		const raw = String(value ?? '').trim();
		if (/^\d+(?:\.\d+)?(px|%|vw|vh|rem|em)$/.test(raw)) {
			return raw;
		}
		if (/^\d+(?:\.\d+)?$/.test(raw)) {
			return `${raw}px`;
		}
		return fallback;
	};

	const pxInputValue = (value: string | undefined): string => {
		const raw = String(value ?? '').trim();
		if (!raw) return '';
		if (/^\d+(?:\.\d+)?$/.test(raw)) {
			return String(Math.round(Number.parseFloat(raw)));
		}
		const pxMatch = raw.match(/^(\d+(?:\.\d+)?)px$/);
		return pxMatch ? String(Math.round(Number.parseFloat(pxMatch[1] ?? '0'))) : '';
	};

	const toPx = (rawInput: string): string => {
		const digits = rawInput.replace(/[^\d.]/g, '').trim();
		if (!digits) return '';
		const parsed = Number.parseFloat(digits);
		if (!Number.isFinite(parsed)) return '';
		return `${Math.round(parsed)}px`;
	};

	const blockProps = useBlockProps();
	const width = normalizeDimension(attributes.width, defaultWidth);
	const height = normalizeDimension(attributes.height, defaultHeight);
	const widthPxInput = pxInputValue(attributes.width);
	const heightPxInput = pxInputValue(attributes.height);
	const [options, setOptions] = React.useState([
		{ label: __('Select your project', 'pdfdraft'), value: '' },
	] as Array<{ label: string; value: string }>);
	const [meta, setMeta] = React.useState(
		{} as Record<string, { label: string; pages?: number }>,
	);
	const [isLoadingProjects, setIsLoadingProjects] = React.useState(true);
	const [projectsLoadFailed, setProjectsLoadFailed] = React.useState(false);
	const [projectsReloadKey, setProjectsReloadKey] = React.useState(0);

	React.useEffect(() => {
		let mounted = true;
		const load = async () => {
			setIsLoadingProjects(true);
			setProjectsLoadFailed(false);
			try {
				const rows = (await apiFetch({
					path: '/pdfdraft/v1/pdf-designs?per_page=100&status=any&context=edit',
				})) as Array<any>;
				if (!mounted || !Array.isArray(rows)) return;
				const rowsWithPdf = rows.filter(
					(row) =>
						row?.hasEmbedPdf === true ||
						typeof row?.hasEmbedPdf === 'undefined',
				);
				const getDesignLabel = (row: any) => {
					const rendered = String(row?.title?.rendered ?? '').trim();
					const slug = String(row?.slug ?? '').trim();
					return rendered || slug || __('Untitled design', 'pdfdraft');
				};
				const mapped = rowsWithPdf.map((row) => ({
					value: String(row?.slug ?? ''),
					label: getDesignLabel(row),
				}));
				const nextMeta = rowsWithPdf.reduce((acc, row) => {
					const slug = String(row?.slug ?? '');
					if (!slug) return acc;
					const pages = row?.content?.pages
						? Object.keys(row.content.pages).length
						: undefined;
					acc[slug] = {
						label: getDesignLabel(row),
						pages,
					};
					return acc;
				}, {} as Record<string, { label: string; pages?: number }>);
				setOptions([
					{ label: __('Select your project', 'pdfdraft'), value: '' },
					...mapped,
				]);
				setMeta(nextMeta);
			} catch {
				if (mounted) {
					setProjectsLoadFailed(true);
				}
				// Keep fallback option only.
			} finally {
				if (mounted) {
					setIsLoadingProjects(false);
				}
			}
		};
		void load();
		return () => {
			mounted = false;
		};
	}, [projectsReloadKey]);

	return (
		<div {...blockProps}>
			<InspectorControls>
				<PanelBody title={__('Embed PDF Settings', 'pdfdraft')}>
					<div style={{ marginBottom: 12 }}>
						<div
							style={{
								fontSize: 11,
								fontWeight: 500,
								textTransform: 'uppercase',
								marginBottom: 4,
								color: '#1e1e1e',
								letterSpacing: 0.4,
							}}
						>
							{__('Project', 'pdfdraft')}
						</div>
						<div
							style={{
								display: 'grid',
								gridTemplateColumns: 'minmax(0, 1fr) auto',
								alignItems: 'stretch',
								columnGap: 4,
							}}
						>
							<div
								style={{
									minWidth: 0,
								}}
							>
								<SelectControl
									label=""
									value={attributes.templateId || ''}
									options={options}
									disabled={isLoadingProjects}
									__nextHasNoMarginBottom
									onChange={(v: string) => setAttributes({ templateId: v })}
								/>
							</div>
						<Button
							variant="secondary"
							disabled={isLoadingProjects}
							onClick={() => setProjectsReloadKey((prev: number) => prev + 1)}
							label={__('Refresh projects', 'pdfdraft')}
							showTooltip
							style={{
								minWidth: 36,
								minHeight: 32,
								height: 32,
								display: 'flex',
								alignItems: 'center',
								justifyContent: 'center',
								paddingLeft: 8,
								paddingRight: 8,
							}}
						>
							<span className="dashicons dashicons-update" aria-hidden="true" />
						</Button>
						</div>
					</div>
					<TextControl
						label={__('Width (px)', 'pdfdraft')}
						help={__(
							`Set embedded PDF width in pixels.`,
							'pdfdraft',
						)}
						value={widthPxInput}
						onChange={(v: string) => {
							setAttributes({
								width: toPx(v),
							});
						}}
					/>
					<TextControl
						label={__('Height (px)', 'pdfdraft')}
						help={__(
							`Set viewer height in pixels.`,
							'pdfdraft',
						)}
						value={heightPxInput}
						onChange={(v: string) => {
							setAttributes({
								height: toPx(v),
							});
						}}
					/>
				</PanelBody>
			</InspectorControls>
			<div
				style={{
					position: 'relative',
					border: '1px solid #d0d5dd',
					borderRadius: 8,
					padding: 18,
					background: '#fff',
				}}
			>
				<div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 18 }}>
					<PdfDraftIcon />
					<div style={{ fontSize: 34, fontWeight: 600, color: '#1f2937' }}>
						{__('PDF Embed - PDFDraft', 'pdfdraft')}
					</div>
				</div>
				<div style={{ marginBottom: 10, color: '#344054', fontSize: 14 }}>
					{__('Select a project', 'pdfdraft')}
				</div>
				{projectsLoadFailed && !isLoadingProjects && (
					<div
						style={{
							marginBottom: 10,
							padding: '10px 12px',
							borderRadius: 6,
							background: '#fef3f2',
							border: '1px solid #fecdca',
							color: '#b42318',
							fontSize: 13,
						}}
					>
						{__('Unable to load projects. Please try again.', 'pdfdraft')}
					</div>
				)}
				<SelectControl
					label=""
					value={attributes.templateId || ''}
					options={options}
					disabled={isLoadingProjects}
					onChange={(v: string) => setAttributes({ templateId: v })}
				/>
				{!!attributes.templateId && (
					<div
						style={{
							marginTop: 12,
							borderRadius: 6,
							border: '1px solid #d0d5dd',
							background: '#f9fafb',
							padding: 12,
							display: 'flex',
							alignItems: 'center',
							justifyContent: 'space-between',
						}}
					>
						<div
							style={{
								display: 'flex',
								alignItems: 'center',
								gap: 10,
							}}
						>
							<div
								style={{
									width: 44,
									height: 44,
									borderRadius: 6,
									background: '#f2f4f7',
									display: 'flex',
									alignItems: 'center',
									justifyContent: 'center',
									flex: 'none',
								}}
							>
								<PdfDraftIcon />
							</div>
							<div>
								<div style={{ color: '#101828', fontSize: 14, fontWeight: 500 }}>
									{meta[attributes.templateId]?.label || attributes.templateId}
								</div>
								<div style={{ color: '#98a2b3', fontSize: 12 }}>
									{meta[attributes.templateId]?.pages
										? `${meta[attributes.templateId]?.pages} Pages`
										: __('Project selected', 'pdfdraft')}
								</div>
							</div>
						</div>
						<div style={{ display: 'flex', alignItems: 'center' }}>
							<button
								type="button"
								disabled={isLoadingProjects}
								onClick={() => setAttributes({ templateId: '' })}
								style={{
									border: 'none',
									background: 'transparent',
									opacity: isLoadingProjects ? 0.5 : 1,
									color: '#e23d3d',
									fontSize: 22,
									cursor: isLoadingProjects ? 'not-allowed' : 'pointer',
									lineHeight: 1,
								}}
								aria-label={__('Clear selected project', 'pdfdraft')}
							>
								&times;
							</button>
						</div>
					</div>
				)}
				<div style={{ marginTop: 10, fontSize: 12, color: '#667085' }}>{`${width} x ${height}`}</div>
				{isLoadingProjects && (
					<div
						style={{
							position: 'absolute',
							inset: 0,
							background: 'rgba(255, 255, 255, 0.72)',
							display: 'flex',
							flexDirection: 'column',
							alignItems: 'center',
							justifyContent: 'center',
							gap: 10,
							borderRadius: 8,
							zIndex: 2,
						}}
					>
						<svg
							width="32"
							height="32"
							viewBox="0 0 50 50"
							aria-hidden="true"
							style={{ display: 'block' }}
						>
							<circle
								cx="25"
								cy="25"
								r="20"
								fill="none"
								stroke="#eaecf0"
								strokeWidth="5"
							/>
							<path
								d="M25 5 A20 20 0 0 1 45 25"
								fill="none"
								stroke="#e50001"
								strokeWidth="5"
								strokeLinecap="round"
							>
								<animateTransform
									attributeName="transform"
									type="rotate"
									from="0 25 25"
									to="360 25 25"
									dur="0.85s"
									repeatCount="indefinite"
								/>
							</path>
						</svg>
						<span style={{ fontSize: 13, color: '#475467' }}>
							{__('Loading projects...', 'pdfdraft')}
						</span>
						<span className="screen-reader-text">
							{__('Loading', 'pdfdraft')}
						</span>
					</div>
				)}
			</div>
		</div>
	);
}
