/** @jsxRuntime classic */

type BlockAttrs = {
	templateId?: string;
	text?: string;


	borderRadius?: string;
	contentJustification?: string;
	buttonWidth?: number;
};

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

const JUSTIFY_OPTIONS = [
	{ label: __('Left', 'pdfdraft'), value: 'left' },
	{ label: __('Center', 'pdfdraft'), value: 'center' },
	{ label: __('Right', 'pdfdraft'), value: 'right' },
];

const JUSTIFY_CSS: Record<string, string> = {
	left: 'flex-start',
	center: 'center',
	right: 'flex-end',
};

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

	const [options, setOptions] = React.useState([
		{ label: __('Select your project', 'pdfdraft'), value: '' },
	] as Array<{ label: string; value: string }>);
	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),
				}));
				setOptions([
					{ label: __('Select your project', 'pdfdraft'), value: '' },
					...mapped,
				]);
			} catch {
				if (mounted) setProjectsLoadFailed(true);
			} finally {
				if (mounted) setIsLoadingProjects(false);
			}
		};
		void load();
		return () => {
			mounted = false;
		};
	}, [projectsReloadKey]);

	const justification = attributes.contentJustification || 'left';

	const blockProps = useBlockProps({ className: 'wp-block-button' });
	const buttonText = String(attributes.text ?? '').trim() || __('Download PDF', 'pdfdraft');

	// Block supports (color, spacing, border) land on blockProps as className/style.
	// We want those on the <a> element, not the wrapper div.
	const { className: blockClassName = '', style: blockStyle, ...wrapperProps } = blockProps as any;
	const allClasses: string[] = blockClassName.split(' ').filter(Boolean);
	const wrapperClasses = allClasses.filter((c: string) => !c.startsWith('has-')).join(' ');
	const buttonExtraClasses = allClasses.filter((c: string) => c.startsWith('has-')).join(' ');
	const buttonClass = ['wp-block-button__link', 'wp-element-button', buttonExtraClasses]
		.filter(Boolean)
		.join(' ');

	const wrapperStyle = {
		display: 'flex',
		justifyContent: JUSTIFY_CSS[justification] ?? 'flex-start',
	};

	return (
		<div {...wrapperProps} className={wrapperClasses} style={wrapperStyle}>
			{/* Settings tab */}
			<InspectorControls>
				<PanelBody title={__('Download 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>
						{projectsLoadFailed && !isLoadingProjects && (
							<div style={{ marginTop: 8, fontSize: 12, color: '#b42318' }}>
								{__('Unable to load projects. Please try again.', 'pdfdraft')}
							</div>
						)}
					</div>

					</PanelBody>
			</InspectorControls>

			{/* Styles tab */}
			<InspectorControls group="styles">
				<PanelBody title={__('Border', 'pdfdraft')}>
					<RangeControl
						label={__('Radius (px)', 'pdfdraft')}
						value={attributes.borderRadius !== '' ? parseInt(attributes.borderRadius || '0', 10) : undefined}
						min={0}
						max={100}
						allowReset
						resetFallbackValue={0}
						onChange={(v: number | undefined) =>
							setAttributes({ borderRadius: v !== undefined ? `${v}px` : '' })
						}
						__nextHasNoMarginBottom
					/>
				</PanelBody>
				<PanelBody title={__('Layout', 'pdfdraft')}>
					<SelectControl
						label={__('Justification', 'pdfdraft')}
						value={justification}
						options={JUSTIFY_OPTIONS}
						onChange={(v: string) => setAttributes({ contentJustification: v })}
						__nextHasNoMarginBottom
					/>
					<div style={{ marginTop: 16 }}>
						<p style={{ margin: '0 0 8px', fontSize: 11, fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.4, color: '#1e1e1e' }}>
							{__('Width', 'pdfdraft')}
						</p>
						<ButtonGroup style={{ width: '100%', display: 'flex' }}>
							{[25, 50, 75, 100].map((w) => (
								<Button
									key={w}
									isPressed={attributes.buttonWidth === w}
									onClick={() =>
										setAttributes({ buttonWidth: attributes.buttonWidth === w ? undefined : w })
									}
									style={{ flex: 1, justifyContent: 'center' }}
									variant={attributes.buttonWidth === w ? 'primary' : undefined}
								>
									{w}%
								</Button>
							))}
						</ButtonGroup>
					</div>
				</PanelBody>
			</InspectorControls>

			<RichText
				tagName="a"
				className={buttonClass}
				style={{
					...blockStyle,
					...(attributes.borderRadius ? { borderRadius: attributes.borderRadius } : {}),
					...(attributes.buttonWidth ? { width: `${attributes.buttonWidth}%` } : {}),
				}}
				value={buttonText}
				allowedFormats={[]}
				onChange={(v: string) => setAttributes({ text: v })}
				placeholder={__('Download PDF', 'pdfdraft')}
				withoutInteractiveFormatting
				aria-label={__('Button text', 'pdfdraft')}
				onClick={(e: any) => e.preventDefault()}
			/>
		</div>
	);
}
