import { Input } from '@pdfdraft/ui/components/input';
import { Switch } from '@pdfdraft/ui/components/switch';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@pdfdraft/ui/components/tooltip';
import { __ } from '@wordpress/i18n';
import type { SectionProps, SettingsSelectOption } from './types';
import { TemplateSelector } from './template-selector';

const CONTROL_MAX_WIDTH = 320;

// ── Info tooltip icon ─────────────────────────────────────────────────────────

function InfoIcon() {
	return (
		<svg
			width="14"
			height="14"
			viewBox="0 0 24 24"
			fill="none"
			stroke="currentColor"
			strokeWidth="2"
			strokeLinecap="round"
			strokeLinejoin="round"
			style={{ display: 'inline-block', flexShrink: 0 }}
		>
			<circle cx="12" cy="12" r="10" />
			<line x1="12" y1="8" x2="12" y2="8" strokeWidth="3" />
			<line x1="12" y1="12" x2="12" y2="16" />
		</svg>
	);
}

// ── Field label with optional tooltip ────────────────────────────────────────

function FieldLabel({ label, tooltip }: { label: string; tooltip?: string }) {
	return (
		<div style={{ minWidth: '200px', display: 'flex', alignItems: 'center', gap: '6px', paddingTop: '4px' }}>
			<span style={{ fontSize: '14px', fontWeight: 600, color: '#1d2327' }}>{label}</span>
			{tooltip && (
				<TooltipProvider delayDuration={200}>
					<Tooltip>
						<TooltipTrigger asChild>
							<span style={{ display: 'flex', alignItems: 'center', color: '#8c8f94', cursor: 'default', lineHeight: 0 }}>
								<InfoIcon />
							</span>
						</TooltipTrigger>
						<TooltipContent style={{ maxWidth: '260px', whiteSpace: 'normal', lineHeight: '1.5' }}>
							{tooltip}
						</TooltipContent>
					</Tooltip>
				</TooltipProvider>
			)}
		</div>
	);
}

// ── Card-select field ─────────────────────────────────────────────────────────

interface CardSelectFieldProps {
	label: string;
	value: string;
	options: SettingsSelectOption[];
	onChange: (value: string) => void;
}

function CardSelectField({ label, value, options, onChange }: CardSelectFieldProps) {
	return (
		<div style={{ display: 'flex', alignItems: 'flex-start', gap: '32px', padding: '20px 0' }}>
			{/* Label column */}
			<div style={{ minWidth: '200px', display: 'flex', alignItems: 'center', paddingTop: '4px' }}>
				<span style={{ fontSize: '14px', fontWeight: 600, color: '#1d2327' }}>{label}</span>
			</div>

			{/* Cards column */}
			<div style={{ display: 'flex', flex: 1, gap: '12px' }}>
				{options.map((option) => {
					const isSelected = value === option.value;
					return (
						<button
							key={option.value}
							type="button"
							onClick={() => onChange(option.value)}
							style={{
								flex: 1,
								textAlign: 'left',
								padding: '16px',
								borderRadius: '10px',
								border: `1.5px solid ${isSelected ? 'hsl(var(--primary))' : '#dcdcde'}`,
								background: '#fff',
								cursor: 'pointer',
								transition: 'border-color 0.15s',
								outline: 'none',
							}}
						>
							<div style={{ fontSize: '15px', fontWeight: 600, color: '#1d2327', marginBottom: '6px' }}>
								{option.label}
							</div>
							{option.description && (
								<div style={{ fontSize: '13px', color: '#646970', lineHeight: '1.5' }}>
									{option.description}
								</div>
							)}
						</button>
					);
				})}
			</div>
		</div>
	);
}

// ── Section ───────────────────────────────────────────────────────────────────

export function InvoicesSection({
	currentMode,
	disableFreeOrderInvoices,
	onDisableFreeOrderInvoicesChange,
	currentInvoiceNumberMode,
	localInvoiceNumberStart,
	onGenerationModeChange,
	onInvoiceNumberModeChange,
	onInvoiceNumberStartChange,
	showMyAccountDownloadButton,
	onMyAccountDownloadButtonChange,
	invoicePrefix,
	invoiceSuffix,
	onInvoicePrefixChange,
	onInvoiceSuffixChange,
	storageCustomFolder,
	storageOrganizeByDate,
	onStorageCustomFolderChange,
	onStorageOrganizeByDateChange,
	generationModeOptions,
	invoiceNumberModeOptions,
	activeDesignSlug,
	onActiveDesignSlugChange,
}: SectionProps) {
	// Build a live path preview for the storage card.
	const now = new Date();
	const year = now.getFullYear().toString();
	const month = String(now.getMonth() + 1).padStart(2, '0');
	const previewParts = ['wp-content/uploads/pdfdraft'];
	if (storageCustomFolder.trim()) previewParts.push(storageCustomFolder.trim());
	if (storageOrganizeByDate) { previewParts.push(year); previewParts.push(month); }
	const pathPreview = previewParts.join('/') + '/';

	return (
		<>
		<TemplateSelector value={activeDesignSlug} onChange={onActiveDesignSlugChange} />

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

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

			{/* PDF Generation Mode */}
			<CardSelectField
				label={__('PDF Generation Mode', 'pdfdraft-pdf-invoices-for-woocommerce')}
				value={currentMode}
				options={generationModeOptions}
				onChange={onGenerationModeChange}
			/>

			{/* Skip Free Orders — only visible when generation mode is automatic */}
			{currentMode === 'automatic' && (
				<>
					<div style={{ display: 'flex', alignItems: 'flex-start', gap: '32px', padding: '20px 0' }}>
						<FieldLabel
							label={__('Skip Free Orders', 'pdfdraft-pdf-invoices-for-woocommerce')}
							tooltip={__('When enabled, invoices will not be auto-generated for orders with a total of 0. Manual download still works.', 'pdfdraft-pdf-invoices-for-woocommerce')}
						/>
						<div style={{ flex: 1 }}>
							<Switch
								checked={disableFreeOrderInvoices}
								onCheckedChange={onDisableFreeOrderInvoicesChange}
							/>
						</div>
					</div>
				</>
			)}


			{/* Invoice Number Mode */}
			<CardSelectField
				label={__('Invoice Number Mode', 'pdfdraft-pdf-invoices-for-woocommerce')}
				value={currentInvoiceNumberMode}
				options={invoiceNumberModeOptions}
				onChange={onInvoiceNumberModeChange}
			/>

			{/* Sequential Start Number — only shown when sequential mode is active */}
			{currentInvoiceNumberMode === 'sequential' && (
				<>
					<hr style={{ margin: 0, border: 'none', borderTop: '1px solid #e2e4e7' }} />
					<div style={{ display: 'flex', alignItems: 'flex-start', gap: '32px', padding: '20px 0' }}>
						<FieldLabel
							label={__('Sequential Start Number', 'pdfdraft-pdf-invoices-for-woocommerce')}
							tooltip={__('If empty, numbering starts from 1.', 'pdfdraft-pdf-invoices-for-woocommerce')}
						/>
						<div style={{ flex: 1 }}>
							<Input
								type="number"
								min={1}
								step={1}
								placeholder="1"
								value={localInvoiceNumberStart}
								onChange={(e) => onInvoiceNumberStartChange(e.target.value)}
								style={{ fontSize: '14px' }}
							/>
						</div>
					</div>
				</>
			)}


			{/* My Account Download Button */}
			<div style={{ display: 'flex', alignItems: 'flex-start', gap: '32px', padding: '20px 0' }}>
				<FieldLabel
					label={__('My Account Download Button', 'pdfdraft-pdf-invoices-for-woocommerce')}
					tooltip={__('Show the invoice download button in the WooCommerce My Account orders page.', 'pdfdraft-pdf-invoices-for-woocommerce')}
				/>
				<div style={{ flex: 1 }}>
					<div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
						<Switch
							checked={showMyAccountDownloadButton}
							onCheckedChange={onMyAccountDownloadButtonChange}
						/>
					</div>
				</div>
			</div>


			{/* Prefix / Suffix */}
			<div style={{ display: 'flex', alignItems: 'flex-start', gap: '32px', padding: '20px 0' }}>
				<FieldLabel
					label={__('Prefix / Suffix', 'pdfdraft-pdf-invoices-for-woocommerce')}
					tooltip={__('Wrap the invoice number with optional text. E.g. prefix "INV-" and suffix "-2024" → INV-1001-2024', 'pdfdraft-pdf-invoices-for-woocommerce')}
				/>
				<div style={{ flex: 1 }}>
					{/* Inline composited row: [prefix input] {{invoice_number}} [suffix input] */}
					<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
						<Input
							type="text"
							placeholder={__('Prefix', 'pdfdraft-pdf-invoices-for-woocommerce')}
							value={invoicePrefix}
							onChange={(e) => onInvoicePrefixChange(e.target.value)}
							style={{ fontSize: '14px', width: '140px', flexShrink: 0 }}
						/>
						<span style={{
							fontSize: '12px',
							fontWeight: 400,
							color: '#8c8f94',
							fontFamily: 'monospace',
							whiteSpace: 'nowrap',
						}}>
							{'{{invoice_number}}'}
						</span>
						<Input
							type="text"
							placeholder={__('Suffix', 'pdfdraft-pdf-invoices-for-woocommerce')}
							value={invoiceSuffix}
							onChange={(e) => onInvoiceSuffixChange(e.target.value)}
							style={{ fontSize: '14px', width: '140px', flexShrink: 0 }}
						/>
					</div>
				</div>
			</div>
		</div>

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

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

			{/* Custom folder */}
			<div style={{ display: 'flex', alignItems: 'flex-start', gap: '32px', padding: '20px 0' }}>
				<FieldLabel
					label={__('Storage Folder', 'pdfdraft-pdf-invoices-for-woocommerce')}
					tooltip={__('Subfolder inside the PDFDraft uploads directory. Leave empty to store in the root.', 'pdfdraft-pdf-invoices-for-woocommerce')}
				/>
				<div style={{ flex: 1 }}>
					<div
						style={{
							display: 'flex',
							alignItems: 'center',
							border: '1px solid #e2e4e7',
							borderRadius: '6px',
							overflow: 'hidden',
							background: '#fff',
							maxWidth: CONTROL_MAX_WIDTH,
							width: '100%',
						}}
					>
						<span style={{
							padding: '8px 10px',
							fontSize: '13px',
							color: '#8c8f94',
							background: '#f6f7f7',
							borderRight: '1px solid #e2e4e7',
							whiteSpace: 'nowrap',
							userSelect: 'none' as const,
						}}>
							wp-content/uploads/pdfdraft/
						</span>
						<Input
							type="text"
							placeholder={__('invoices', 'pdfdraft-pdf-invoices-for-woocommerce')}
							value={storageCustomFolder}
							onChange={(e) => onStorageCustomFolderChange(e.target.value.replace(/[^a-zA-Z0-9_\-]/g, ''))}
							style={{ fontSize: '14px', border: 'none', borderRadius: 0, boxShadow: 'none', flex: 1 }}
						/>
					</div>
				</div>
			</div>


			{/* Organize by date */}
			<div style={{ display: 'flex', alignItems: 'flex-start', gap: '32px', padding: '20px 0' }}>
				<FieldLabel
					label={__('Organize by Year / Month', 'pdfdraft-pdf-invoices-for-woocommerce')}
					tooltip={__('Automatically sort invoices into year/month sub-folders (e.g. 2025/01/).', 'pdfdraft-pdf-invoices-for-woocommerce')}
				/>
				<div style={{ flex: 1 }}>
					<div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
						<Switch
							checked={storageOrganizeByDate}
							onCheckedChange={onStorageOrganizeByDateChange}
						/>
					</div>
				</div>
			</div>


			{/* Live path preview */}
			<div style={{ display: 'flex', alignItems: 'flex-start', gap: '32px', padding: '20px 0' }}>
				<FieldLabel
					label={__('Save Location', 'pdfdraft-pdf-invoices-for-woocommerce')}
					tooltip={__('Preview of where invoices will be saved based on current settings.', 'pdfdraft-pdf-invoices-for-woocommerce')}
				/>
				<div style={{ flex: 1 }}>
					<code style={{
						display: 'inline-block',
						fontSize: '13px',
						color: '#3858e9',
						background: '#f0f4ff',
						border: '1px solid #c7d4f8',
						borderRadius: '6px',
						padding: '6px 12px',
						fontFamily: 'monospace',
					}}>
						{pathPreview}
					</code>
				</div>
			</div>
		</div>
		</>
	);
}
