import { Link } from '@tanstack/react-router'
import { parseMobilePath, parseWebPath } from '../routes.tsx'

interface IndexPageProps {
	webModules: Record<string, unknown>
	mobileModules: Record<string, unknown>
}

interface TaskEntry {
	task: string
	hasWeb: boolean
	hasMobile: boolean
}

export function IndexPage({ webModules, mobileModules }: IndexPageProps) {
	// Group entries by workflow, merging web and mobile tasks.
	const grouped = new Map<string, Map<string, TaskEntry>>()

	for (const path of Object.keys(webModules)) {
		const parsed = parseWebPath(path)
		if (!parsed) continue

		if (!grouped.has(parsed.workflow)) {
			grouped.set(parsed.workflow, new Map())
		}
		const tasks = grouped.get(parsed.workflow) ?? new Map<string, TaskEntry>()
		grouped.set(parsed.workflow, tasks)
		const existing = tasks.get(parsed.task)
		if (existing) {
			existing.hasWeb = true
		} else {
			tasks.set(parsed.task, { task: parsed.task, hasWeb: true, hasMobile: false })
		}
	}

	for (const path of Object.keys(mobileModules)) {
		const parsed = parseMobilePath(path)
		if (!parsed) continue

		if (!grouped.has(parsed.workflow)) {
			grouped.set(parsed.workflow, new Map())
		}
		const tasks = grouped.get(parsed.workflow) ?? new Map<string, TaskEntry>()
		grouped.set(parsed.workflow, tasks)
		const existing = tasks.get(parsed.widget)
		if (existing) {
			existing.hasMobile = true
		} else {
			tasks.set(parsed.widget, { task: parsed.widget, hasWeb: false, hasMobile: true })
		}
	}

	// Sort workflows and tasks.
	const sortedWorkflows = [...grouped.entries()].sort(([a], [b]) => a.localeCompare(b))

	return (
		<div style={styles.container}>
			<header style={styles.header}>
				<h1 style={styles.title}>Workflow Preview</h1>
				<span style={styles.badge}>
					{Object.keys(webModules).length + Object.keys(mobileModules).length} components
				</span>
			</header>

			{sortedWorkflows.map(([workflow, tasks]) => (
				<section key={workflow} style={styles.section}>
					<h2 style={styles.sectionTitle}>{formatWorkflowName(workflow)}</h2>

					<div style={styles.taskList}>
						{[...tasks.values()]
							.sort((a, b) => a.task.localeCompare(b.task))
							.map((entry) => (
								<div key={entry.task} style={styles.taskRow}>
									<span style={styles.taskName}>{entry.task.replace(/-/g, ' ')}</span>
									<div style={styles.links}>
										{entry.hasWeb && (
											<Link
												to={`/workflows/${workflow}/web/${entry.task}`}
												style={styles.link}
												data-platform="web"
											>
												web
											</Link>
										)}
										{entry.hasMobile && (
											<Link
												to={`/workflows/${workflow}/mobile/${entry.task}`}
												style={{
													...styles.link,
													borderColor: '#d1d5db',
													color: '#6366f1',
												}}
												data-platform="mobile"
											>
												mobile
											</Link>
										)}
									</div>
								</div>
							))}
					</div>
				</section>
			))}

			{sortedWorkflows.length === 0 && (
				<div style={styles.empty}>
					<p>No workflows found.</p>
					<p style={{ fontSize: '0.84rem', color: '#84828e', marginTop: 8 }}>
						{
							'Make sure your workflows/ directory contains web (*/web/*/main.tsx) or mobile (*/mobile/*.rfwtxt) files.'
						}
					</p>
				</div>
			)}
		</div>
	)
}

function formatWorkflowName(name: string): string {
	// "001-demo-workflow" -> "001 demo workflow"
	return name.replace(/-/g, ' ')
}

const styles = {
	container: {
		maxWidth: 720,
		margin: '0 auto',
		padding: '2rem 1.5rem',
	} satisfies React.CSSProperties,

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

	title: {
		fontSize: '1.25rem',
		fontWeight: 700,
		color: '#102a43',
	} satisfies React.CSSProperties,

	badge: {
		fontSize: '0.7rem',
		fontWeight: 600,
		color: '#829ab1',
		backgroundColor: '#f0f4f8',
		padding: '0.2rem 0.6rem',
		borderRadius: 99,
	} satisfies React.CSSProperties,

	section: {
		marginBottom: '2rem',
	} satisfies React.CSSProperties,

	sectionTitle: {
		fontSize: '0.75rem',
		fontWeight: 600,
		color: '#829ab1',
		textTransform: 'uppercase' as const,
		letterSpacing: '0.05em',
		marginBottom: '0.75rem',
	} satisfies React.CSSProperties,

	taskList: {
		display: 'flex',
		flexDirection: 'column' as const,
		gap: '0.5rem',
	} satisfies React.CSSProperties,

	taskRow: {
		display: 'flex',
		alignItems: 'center',
		justifyContent: 'space-between',
		padding: '0.75rem 1rem',
		borderRadius: 10,
		border: '1px solid #e2e8f0',
		backgroundColor: '#fff',
	} satisfies React.CSSProperties,

	taskName: {
		fontSize: '0.9rem',
		fontWeight: 500,
		color: '#334e68',
	} satisfies React.CSSProperties,

	links: {
		display: 'flex',
		gap: '0.5rem',
	} satisfies React.CSSProperties,

	link: {
		fontSize: '0.72rem',
		fontWeight: 600,
		textDecoration: 'none',
		padding: '0.25rem 0.6rem',
		borderRadius: 6,
		border: '1px solid #ccfbf1',
		color: '#0d9488',
		backgroundColor: '#f0fdfa',
		transition: 'background-color 0.15s, border-color 0.15s',
	} satisfies React.CSSProperties,

	empty: {
		textAlign: 'center' as const,
		padding: '3rem 1rem',
		color: '#65636d',
	} satisfies React.CSSProperties,
}
