import { Skeleton } from '@pdfdraft/ui/components/skeleton';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@pdfdraft/ui/components/tooltip';
import apiFetch from '@wordpress/api-fetch';
import { __ } from '@wordpress/i18n';
import { addQueryArgs } from '@wordpress/url';
import { useQuery } from '@tanstack/react-query';
import { getWooCommerceSettingsLocalized } from '../utils';

// ─── Types ────────────────────────────────────────────────────────────────────

interface Design {
	id: number;
	slug: string;
	title: { rendered: string };
	status: 'publish' | 'draft';
}

export interface TemplateSelectorProps {
	value: string;
	onChange: (slug: string) => void;
}

// ─── Localized data ───────────────────────────────────────────────────────────

const localizedData = getWooCommerceSettingsLocalized<{ editor_url_for_woo?: string }>() ?? {};
const EDITOR_URL =
	localizedData.editor_url_for_woo ??
	'admin.php?page=pdfdraft#/woo/new';

// ─── Helpers ──────────────────────────────────────────────────────────────────

function decodeHtml(html: string): string {
	try {
		const el = document.createElement('div');
		el.innerHTML = html;
		return el.textContent ?? html;
	} catch {
		return html;
	}
}

function InfoIcon() {
	return (
		<svg
			width="14"
			height="14"
			viewBox="0 0 16 16"
			fill="none"
			aria-hidden="true"
		>
			<circle cx="8" cy="8" r="7" stroke="currentColor" strokeWidth="1.5" />
			<path d="M8 7v5M8 5.5v.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
		</svg>
	);
}

// ─── Component ────────────────────────────────────────────────────────────────

export function TemplateSelector({ value, onChange }: TemplateSelectorProps) {
	const { data: designs = [], isLoading } = useQuery({
		queryKey: ['woo-pdf-designs-published'],
		queryFn: () =>
			apiFetch<Design[]>({
				path: addQueryArgs('/pdfdraft/v1/pdf-designs', {
					context: 'edit',
					status: ['publish'],
					per_page: 100,
				}),
			}),
		staleTime: 30_000,
		refetchOnWindowFocus: false,
	});

	return (
		<div
			style={{
				background: '#fff',
				borderRadius: '15px',
				border: '1px solid #e2e4e7',
				padding: '4px 24px 8px',
			}}
		>
			{/* Section title */}
			<div style={{ padding: '20px 0 16px' }}>
				<h3 style={{ margin: 0, fontSize: '18px', fontWeight: 600, color: '#1d2327' }}>
					{__('Invoice Template', 'pdfdraft-pdf-invoices-for-woocommerce')}
				</h3>
			</div>

			<hr style={{ margin: 0, border: 'none', borderTop: '1px solid #e2e4e7' }} />

			{/* Field row */}
			<div style={{ display: 'flex', alignItems: 'flex-start', gap: '32px', padding: '20px 0' }}>
				{/* Label */}
				<div
					style={{
						minWidth: '200px',
						display: 'flex',
						alignItems: 'center',
						gap: '6px',
						paddingTop: '6px',
					}}
				>
					<span style={{ fontSize: '14px', fontWeight: 600, color: '#1d2327' }}>
						{__('Active Template', 'pdfdraft-pdf-invoices-for-woocommerce')}
					</span>
					<TooltipProvider delayDuration={200}>
						<Tooltip>
							<TooltipTrigger asChild>
								<span
									style={{
										display: 'inline-flex',
										alignItems: 'center',
										color: '#8c8f94',
										cursor: 'default',
										lineHeight: 0,
									}}
								>
									<InfoIcon />
								</span>
							</TooltipTrigger>
							<TooltipContent style={{ maxWidth: '260px', whiteSpace: 'normal', lineHeight: '1.5' }}>
								{__(
									'The selected design will be used to generate all WooCommerce invoice PDFs.',
									'pdfdraft-pdf-invoices-for-woocommerce',
								)}
							</TooltipContent>
						</Tooltip>
					</TooltipProvider>
				</div>

				{/* Control */}
				<div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: '10px', flexWrap: 'wrap' }}>
					{isLoading ? (
						<Skeleton className="h-9" style={{ width: 300 }} />
					) : (
						<select
							value={value}
							onChange={(e) => onChange(e.target.value)}
							style={{
								height: 36,
								borderRadius: 6,
								border: '1px solid #d0d5dd',
								padding: '0 10px',
								fontSize: 13,
								color: value ? '#1d2327' : '#9ca3af',
								maxWidth: 300,
								width: '100%',
							}}
						>
							<option value="" style={{ color: '#9ca3af' }}>
								{__('— Select a template —', 'pdfdraft-pdf-invoices-for-woocommerce')}
							</option>
							{designs.map((design) => (
								<option key={design.id} value={design.slug} style={{ color: '#1d2327' }}>
									{decodeHtml(design.title?.rendered ?? design.slug)}
								</option>
							))}
						</select>
					)}

					<a
						href={EDITOR_URL}
						target="_blank"
						rel="noreferrer"
						style={{
							fontSize: 13,
							color: 'hsl(var(--primary))',
							whiteSpace: 'nowrap',
							textDecoration: 'none',
						}}
					>
						{__('+ Create New', 'pdfdraft-pdf-invoices-for-woocommerce')}
					</a>
				</div>
			</div>
		</div>
	);
}
