import { Link } from '@tanstack/react-router'
import { useEffect, useState } from 'react'

interface MobilePreviewProps {
	workflow: string
	widget: string
}

export function MobilePreview({ workflow, widget }: MobilePreviewProps) {
	const rfwtxtPath = `./mobile/workflows/${workflow}/mobile/${widget}.rfwtxt`
	const flutterFilePath = `./workflows/${workflow}/mobile/${widget}.rfwtxt`
	const iframeSrc = `./mobile/?file=${encodeURIComponent(flutterFilePath)}&bare=true`
	const [flutterAvailable, setFlutterAvailable] = useState<boolean | null>(null)
	const [rfwtxtSource, setRfwtxtSource] = useState<string | null>(null)
	const [showHeader] = useState(() => !window.location.hash.includes('header=false'))

	useEffect(() => {
		fetch('./mobile/flutter_bootstrap.js', { method: 'HEAD' })
			.then((res) => {
				const ct = res.headers.get('content-type') ?? ''
				setFlutterAvailable(res.ok && ct.includes('javascript'))
			})
			.catch(() => {
				setFlutterAvailable(false)
			})
	}, [])

	useEffect(() => {
		if (flutterAvailable === false) {
			fetch(rfwtxtPath, { headers: { Accept: 'text/plain' } })
				.then((res) => (res.ok ? res.text() : null))
				.then((text) => setRfwtxtSource(text))
				.catch(() => setRfwtxtSource(null))
		}
	}, [flutterAvailable, rfwtxtPath])

	return (
		<div style={styles.wrapper}>
			{showHeader && (
				<nav style={styles.nav}>
					<Link to="/" style={styles.backLink}>
						&larr; All workflows
					</Link>
					<span style={styles.breadcrumb}>
						{workflow} / mobile / {widget}
					</span>
				</nav>
			)}

			<div style={styles.container}>
				{flutterAvailable === null && <div style={styles.loading}>Loading...</div>}

				{flutterAvailable === true && (
					<div style={styles.phone}>
						<iframe src={iframeSrc} title={`Mobile preview: ${widget}`} style={styles.iframe} />
					</div>
				)}

				{flutterAvailable === false && (
					<div style={styles.fallback}>
						<div style={styles.fallbackHeader}>
							<span style={styles.mobileBadge}>mobile</span>
							<span style={styles.filename}>
								{workflow}/mobile/{widget}.rfwtxt
							</span>
						</div>
						<div style={styles.notice}>
							{'Mobile preview is not built. Run "task build:flutter" to enable live rendering.'}
						</div>
						{rfwtxtSource ? (
							<pre style={styles.code}>
								<code>{rfwtxtSource}</code>
							</pre>
						) : (
							<div style={styles.notice}>{'rfwtxt file not found.'}</div>
						)}
					</div>
				)}
			</div>
		</div>
	)
}

const styles = {
	wrapper: {
		minHeight: '100vh',
		backgroundColor: '#fdfcfd',
	} satisfies React.CSSProperties,

	nav: {
		display: 'flex',
		alignItems: 'center',
		gap: '1rem',
		padding: '0.75rem 1.5rem',
		borderBottom: '1px solid #e2e8f0',
		backgroundColor: '#fff',
	} satisfies React.CSSProperties,

	backLink: {
		fontSize: '0.84rem',
		color: '#0d9488',
		textDecoration: 'none',
		fontWeight: 500,
	} satisfies React.CSSProperties,

	breadcrumb: {
		fontSize: '0.75rem',
		color: '#829ab1',
		fontFamily: '"Geist Mono", monospace',
	} satisfies React.CSSProperties,

	container: {
		display: 'flex',
		justifyContent: 'center',
		padding: '2rem',
	} satisfies React.CSSProperties,

	loading: {
		padding: '3rem',
		color: '#829ab1',
	} satisfies React.CSSProperties,

	phone: {
		width: 420,
		height: 720,
		borderRadius: 12,
		border: '1px solid #e2e8f0',
		backgroundColor: '#fff',
		boxShadow: '0 4px 24px rgba(0,0,0,0.06)',
		overflow: 'hidden',
	} satisfies React.CSSProperties,

	iframe: {
		width: '100%',
		height: '100%',
		border: 'none',
	} satisfies React.CSSProperties,

	fallback: {
		width: 720,
		maxWidth: '100%',
	} satisfies React.CSSProperties,

	fallbackHeader: {
		display: 'flex',
		alignItems: 'center',
		gap: '0.75rem',
		marginBottom: '0.75rem',
	} satisfies React.CSSProperties,

	mobileBadge: {
		fontSize: '0.72rem',
		fontWeight: 600,
		padding: '0.25rem 0.6rem',
		borderRadius: 6,
		border: '1px solid #d1d5db',
		color: '#6366f1',
		backgroundColor: '#eef2ff',
	} satisfies React.CSSProperties,

	filename: {
		fontSize: '0.8rem',
		color: '#829ab1',
		fontFamily: '"Geist Mono", monospace',
	} satisfies React.CSSProperties,

	notice: {
		fontSize: '0.8rem',
		color: '#84828e',
		padding: '0.75rem 1rem',
		backgroundColor: '#fef3c7',
		border: '1px solid #fcd34d',
		borderRadius: 8,
		marginBottom: '1rem',
	} satisfies React.CSSProperties,

	code: {
		fontSize: '0.78rem',
		lineHeight: 1.6,
		fontFamily: '"Geist Mono", monospace',
		backgroundColor: '#1e293b',
		color: '#e2e8f0',
		padding: '1.25rem',
		borderRadius: 10,
		overflow: 'auto',
		maxHeight: 600,
		whiteSpace: 'pre' as const,
		margin: 0,
	} satisfies React.CSSProperties,
}
