import React from 'react';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { Skeleton } from '@pdfdraft/ui/components/skeleton';
import {
	Tooltip,
	TooltipContent,
	TooltipProvider,
	TooltipTrigger,
} from '@pdfdraft/ui/components/tooltip';

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

interface ProjectOption {
	id: number;
	title: string;
	edit_url: string;
}

interface PostTypeSettings {
	enabled: boolean;
	project_id: number;
	pdf_style: 'default' | 'custom';
}

interface ButtonSettings {
	text: string;
	position: 'before_content' | 'after_content' | 'floating';
	css_class: string;
}

interface PostsToPdfSettingsData {
	enabled: boolean;
	include_images: boolean;
	posts: PostTypeSettings;
	pages: PostTypeSettings;
	button: ButtonSettings;
	filename_pattern: string;
}

interface ApiResponse {
	settings: PostsToPdfSettingsData;
	projects: ProjectOption[];
}

export interface PostsToPdfSettingsHandle {
	save: () => Promise<boolean>;
}

interface PostsToPdfSettingsProps {
	onSavingChange?: (saving: boolean) => void;
}

const DEFAULTS: PostsToPdfSettingsData = {
	enabled: false,
	include_images: true,
	posts: { enabled: false, project_id: 0, pdf_style: 'default' },
	pages: { enabled: false, project_id: 0, pdf_style: 'default' },
	button: { text: 'Download PDF', position: 'after_content', css_class: '' },
	filename_pattern: '{post_title}.pdf',
};

const CONTROL_MAX_WIDTH = 320;

const controlBaseStyle: React.CSSProperties = {
	height: 36,
	borderRadius: 6,
	border: '1px solid #d0d5dd',
	padding: '0 12px',
	fontSize: 13,
	maxWidth: CONTROL_MAX_WIDTH,
	width: '100%',
};

// ─── Skeleton ─────────────────────────────────────────────────────────────────

function SectionCardSkeleton({ rows = 1 }: { rows?: number }) {
	return (
		<div
			style={{
				background: '#fff',
				borderRadius: '10px',
				border: '1px solid #e2e4e7',
				padding: '24px',
				marginBottom: '20px',
			}}
		>
			<div
				style={{
					margin: '0 0 16px',
					paddingBottom: 16,
					borderBottom: '1px solid #e2e4e7',
				}}
			>
				<Skeleton className="h-5 w-40" />
			</div>
			{Array.from({ length: rows }).map((_, i) => (
				<div
					key={i}
					style={{
						display: 'grid',
						gridTemplateColumns: '220px 1fr',
						gap: '12px 24px',
						alignItems: 'start',
						marginBottom: i < rows - 1 ? 16 : 0,
					}}
				>
					<Skeleton className="h-3.5 w-28" />
					<Skeleton className="h-6 w-10 rounded-full" />
				</div>
			))}
		</div>
	);
}

/** Content-only skeleton — header Save is on the parent settings page. */
export function PostsToPdfSettingsSkeleton() {
	return (
		<div style={{ padding: '24px 32px' }}>
			<SectionCardSkeleton rows={1} />
		</div>
	);
}

// ─── Sub-components ───────────────────────────────────────────────────────────

function Toggle({
	checked,
	onChange,
	label,
}: {
	checked: boolean;
	onChange: (v: boolean) => void;
	label: string;
}) {
	return (
		<label style={{ display: 'flex', alignItems: 'center', gap: '10px', cursor: 'pointer' }}>
			<span
				role="switch"
				aria-checked={checked}
				tabIndex={0}
				onClick={() => onChange(!checked)}
				onKeyDown={(e) => (e.key === ' ' || e.key === 'Enter') && onChange(!checked)}
				style={{
					display: 'inline-block',
					width: '40px',
					height: '22px',
					borderRadius: '11px',
					background: checked ? 'hsl(var(--primary))' : '#d1d5db',
					position: 'relative',
					transition: 'background 0.2s',
					flexShrink: 0,
					cursor: 'pointer',
				}}
			>
				<span
					style={{
						position: 'absolute',
						top: '3px',
						left: checked ? '21px' : '3px',
						width: '16px',
						height: '16px',
						borderRadius: '50%',
						background: '#fff',
						transition: 'left 0.2s',
						boxShadow: '0 1px 3px rgba(0,0,0,.2)',
					}}
				/>
			</span>
			<span style={{ fontSize: 14, color: '#1d2327' }}>{label}</span>
		</label>
	);
}

function SectionCard({
	title,
	children,
}: {
	title: string;
	children: React.ReactNode;
}) {
	return (
		<div
			style={{
				background: '#fff',
				borderRadius: '10px',
				border: '1px solid #e2e4e7',
				padding: '24px',
				marginBottom: '20px',
			}}
		>
			<h3
				style={{
					margin: '0 0 16px',
					fontSize: 18,
					fontWeight: 600,
					color: '#1d2327',
					paddingBottom: 16,
					borderBottom: '1px solid #e2e4e7',
				}}
			>
				{title}
			</h3>
			{children}
		</div>
	);
}

function ProjectSelect({
	value,
	onChange,
	projects,
}: {
	value: number;
	onChange: (id: number) => void;
	projects: ProjectOption[];
}) {
	return (
		<select
			value={value}
			onChange={(e) => onChange(parseInt(e.target.value, 10))}
			style={{
				...controlBaseStyle,
				padding: '0 10px',
				color: value === 0 ? '#9ca3af' : '#1d2327',
			}}
		>
			<option value={0} style={{ color: '#9ca3af' }}>{__('— Select a template —', 'pdfdraft')}</option>
			{projects.map((p) => (
				<option key={p.id} value={p.id} style={{ color: '#1d2327' }}>
					{p.title}
				</option>
			))}
		</select>
	);
}

function FieldRow({
	label,
	tooltip,
	children,
}: {
	label: string;
	tooltip?: string;
	children: React.ReactNode;
}) {
	return (
		<div
			style={{
				display: 'grid',
				gridTemplateColumns: '220px 1fr',
				gap: '12px 24px',
				alignItems: 'start',
				marginBottom: 16,
			}}
		>
			<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
				<span style={{ fontSize: 14, fontWeight: 600, color: '#1d2327' }}>{label}</span>
				{tooltip && (
					<Tooltip>
						<TooltipTrigger asChild>
							<span
								style={{ display: 'inline-flex', alignItems: 'center', cursor: 'default', color: '#9ca3af' }}
								aria-label={tooltip}
							>
								<svg width="14" height="14" viewBox="0 0 16 16" fill="none">
									<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>
							</span>
						</TooltipTrigger>
						<TooltipContent side="right">
							<span style={{ maxWidth: 220, display: 'block' }}>{tooltip}</span>
						</TooltipContent>
					</Tooltip>
				)}
			</div>
			<div>{children}</div>
		</div>
	);
}

// ─── Main component ───────────────────────────────────────────────────────────

export const PostsToPdfSettings = React.forwardRef<
	PostsToPdfSettingsHandle,
	PostsToPdfSettingsProps
>(function PostsToPdfSettings(
	{ onSavingChange },
	ref,
) {
	const [isLoading, setIsLoading] = React.useState(true);
	const [isSaving, setIsSaving]   = React.useState(false);
	const [settings, setSettings]   = React.useState<PostsToPdfSettingsData>(DEFAULTS);
	const [projects, setProjects]   = React.useState<ProjectOption[]>([]);

	React.useEffect(() => {
		let mounted = true;
		void apiFetch<ApiResponse>({ path: '/pdfdraft/v1/posts-to-pdf/settings' })
			.then((res) => {
				if (!mounted) return;
				setSettings({ ...DEFAULTS, ...res.settings });
				setProjects(res.projects ?? []);
			})
			.catch(() => {})
			.finally(() => { if (mounted) setIsLoading(false); });
		return () => { mounted = false; };
	}, []);

	const save = async (): Promise<boolean> => {
		setIsSaving(true);
		onSavingChange?.(true);
		try {
			await apiFetch({
				path:   '/pdfdraft/v1/posts-to-pdf/settings',
				method: 'POST',
				data:   { settings },
			});
			return true;
		} catch (err) {
			return false;
		} finally {
			setIsSaving(false);
			onSavingChange?.(false);
		}
	};

	React.useImperativeHandle(
		ref,
		() => ({
			save,
		}),
		[save],
	);

	const set = <K extends keyof PostsToPdfSettingsData>(
		key: K,
		value: PostsToPdfSettingsData[K],
	) => setSettings((prev) => ({ ...prev, [key]: value }));

	const setPostType = (
		type: 'posts' | 'pages',
		patch: Partial<PostTypeSettings>,
	) => setSettings((prev) => ({ ...prev, [type]: { ...prev[type], ...patch } }));

	const setButton = (patch: Partial<ButtonSettings>) =>
		setSettings((prev) => ({ ...prev, button: { ...prev.button, ...patch } }));

	if (isLoading) return <PostsToPdfSettingsSkeleton />;

	return (
		<TooltipProvider delayDuration={200}>
			<div style={{ padding: '24px 32px' }}>
				{/* ── Global enable ─────────────────────────────────────────── */}
				<SectionCard title={__('Posts to PDF', 'pdfdraft')}>
					<FieldRow
						label={__('Enable', 'pdfdraft')}
						tooltip={__('Allow visitors to download posts and pages as PDFs using your PDFDraft templates.', 'pdfdraft')}
					>
						<Toggle
							checked={settings.enabled}
							onChange={(v) => set('enabled', v)}
							label={__('Enable Posts to PDF', 'pdfdraft')}
						/>
					</FieldRow>
				</SectionCard>

				{settings.enabled && (
					<>
						{/* ── Posts ────────────────────────────────────────────── */}
						<SectionCard title={__('Posts', 'pdfdraft')}>
							<FieldRow label={__('Enable for Posts', 'pdfdraft')}>
								<Toggle
									checked={settings.posts.enabled}
									onChange={(v) => setPostType('posts', { enabled: v })}
									label={__('Add download button to posts', 'pdfdraft')}
								/>
							</FieldRow>
							{settings.posts.enabled && (
								<>
									<FieldRow
										label={__('PDF style', 'pdfdraft')}
										tooltip={__("Default renders the post's own HTML directly. Custom template uses a PDFDraft template to design the layout.", 'pdfdraft')}
									>
										<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
											<label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', fontSize: 13 }}>
												<input
													type="radio"
													name="posts_pdf_style"
													value="default"
													checked={settings.posts.pdf_style === 'default'}
													onChange={() => setPostType('posts', { pdf_style: 'default' })}
													style={{ margin: 0, outline: 0, boxShadow: 'none' }}
												/>
												<span style={{ color: '#1d2327' }}>{__('Default — no template', 'pdfdraft')}</span>
											</label>
											<label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', fontSize: 13 }}>
												<input
													type="radio"
													name="posts_pdf_style"
													value="custom"
													checked={settings.posts.pdf_style === 'custom'}
													onChange={() => setPostType('posts', { pdf_style: 'custom' })}
													style={{ margin: 0, outline: 0, boxShadow: 'none' }}
												/>
												<span style={{ color: '#1d2327' }}>{__('Use a custom template', 'pdfdraft')}</span>
											</label>
										</div>
									</FieldRow>
									{settings.posts.pdf_style === 'custom' && (
										<FieldRow
											label={__('Template', 'pdfdraft')}
											tooltip={__('Select which template to use when generating PDFs for posts.', 'pdfdraft')}
										>
											<div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
												<ProjectSelect
													value={settings.posts.project_id}
													onChange={(id) => setPostType('posts', { project_id: id })}
													projects={projects}
												/>
												<a
													href={newDesignUrl()}
													target="_blank"
													rel="noreferrer"
													style={{ fontSize: 13, color: 'hsl(var(--primary))', whiteSpace: 'nowrap' }}
												>
													{__('+ Create New', 'pdfdraft')}
												</a>
											</div>
										</FieldRow>
									)}
								</>
							)}
						</SectionCard>

						{/* ── Pages ────────────────────────────────────────────── */}
						<SectionCard title={__('Pages', 'pdfdraft')}>
							<FieldRow label={__('Enable for Pages', 'pdfdraft')}>
								<Toggle
									checked={settings.pages.enabled}
									onChange={(v) => setPostType('pages', { enabled: v })}
									label={__('Add download button to pages', 'pdfdraft')}
								/>
							</FieldRow>
							{settings.pages.enabled && (
								<>
									<FieldRow
										label={__('PDF style', 'pdfdraft')}
										tooltip={__("Default renders the page's own HTML directly. Custom template uses a PDFDraft template to design the layout.", 'pdfdraft')}
									>
										<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
											<label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', fontSize: 13 }}>
												<input
													type="radio"
													name="pages_pdf_style"
													value="default"
													checked={settings.pages.pdf_style === 'default'}
													onChange={() => setPostType('pages', { pdf_style: 'default' })}
													style={{ margin: 0, outline: 0, boxShadow: 'none' }}
												/>
												<span style={{ color: '#1d2327' }}>{__('Default — no template', 'pdfdraft')}</span>
											</label>
											<label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', fontSize: 13 }}>
												<input
													type="radio"
													name="pages_pdf_style"
													value="custom"
													checked={settings.pages.pdf_style === 'custom'}
													onChange={() => setPostType('pages', { pdf_style: 'custom' })}
													style={{ margin: 0, outline: 0, boxShadow: 'none' }}
												/>
												<span style={{ color: '#1d2327' }}>{__('Use a custom template', 'pdfdraft')}</span>
											</label>
										</div>
									</FieldRow>
									{settings.pages.pdf_style === 'custom' && (
										<FieldRow
											label={__('Template', 'pdfdraft')}
											tooltip={__('Select which template to use when generating PDFs for pages.', 'pdfdraft')}
										>
											<div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
												<ProjectSelect
													value={settings.pages.project_id}
													onChange={(id) => setPostType('pages', { project_id: id })}
													projects={projects}
												/>
												<a
													href={newDesignUrl()}
													target="_blank"
													rel="noreferrer"
													style={{ fontSize: 13, color: 'hsl(var(--primary))', whiteSpace: 'nowrap' }}
												>
													{__('+ Create New', 'pdfdraft')}
												</a>
											</div>
										</FieldRow>
									)}
								</>
							)}
						</SectionCard>

						{/* ── Download button ───────────────────────────────────── */}
						<SectionCard title={__('Download Button', 'pdfdraft')}>
							<FieldRow label={__('Button Text', 'pdfdraft')}>
								<input
									type="text"
									value={settings.button.text}
									onChange={(e) => setButton({ text: e.target.value })}
									placeholder="Download PDF"
									style={controlBaseStyle}
								/>
							</FieldRow>
							<FieldRow
								label={__('Position', 'pdfdraft')}
								tooltip={__('Where to place the button relative to post content.', 'pdfdraft')}
							>
								<select
									value={settings.button.position}
									onChange={(e) => setButton({ position: e.target.value as ButtonSettings['position'] })}
									style={{ ...controlBaseStyle, padding: '0 10px' }}
								>
									<option value="before_content">{__('Before Content', 'pdfdraft')}</option>
									<option value="after_content">{__('After Content', 'pdfdraft')}</option>
									<option value="floating">{__('Floating (bottom-right)', 'pdfdraft')}</option>
								</select>
							</FieldRow>
							<FieldRow
								label={__('CSS Class', 'pdfdraft')}
								tooltip={__('Optional. Add custom CSS classes to the button wrapper.', 'pdfdraft')}
							>
								<input
									type="text"
									value={settings.button.css_class}
									onChange={(e) => setButton({ css_class: e.target.value })}
									placeholder="my-custom-class"
									style={controlBaseStyle}
								/>
							</FieldRow>
							<FieldRow
								label={__('Include Post Images', 'pdfdraft')}
								tooltip={__('When enabled, images inside post content are included in the generated PDF.', 'pdfdraft')}
							>
								<Toggle
									checked={settings.include_images}
									onChange={(v) => set('include_images', v)}
									label={__('Include images from post content', 'pdfdraft')}
								/>
							</FieldRow>
						</SectionCard>

						{/* ── Filename pattern ──────────────────────────────────── */}
						<SectionCard title={__('PDF Filename', 'pdfdraft')}>
							<FieldRow
								label={__('Filename Pattern', 'pdfdraft')}
								tooltip={__('Pattern for the downloaded PDF filename. Available tokens: {post_title}, {post_date}, {post_id}, {post_type}', 'pdfdraft')}
							>
								<div>
									<input
										type="text"
										value={settings.filename_pattern}
										onChange={(e) => set('filename_pattern', e.target.value)}
										placeholder="{post_title}.pdf"
										style={controlBaseStyle}
									/>
									<p style={{ fontSize: 12, color: '#6b7280', marginTop: 6, marginBottom: 0 }}>
										{__('Example: {post_title}-{post_date}.pdf', 'pdfdraft')}
									</p>
								</div>
							</FieldRow>
						</SectionCard>
					</>
				)}
			</div>
		</TooltipProvider>
	);
});

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

function newDesignUrl(): string {
	const url = new URL('admin.php', window.location.href);
	url.searchParams.set('page', 'pdfdraft');
	return url.toString();
}
