<script>
	import { debounce, escapeHTML, escapeRegExp, strHashHSL, datetime_dtstr, filter_pattern, filter_test, filter_mark, filter_snippets } from '$lib/util.js';

	export let data;

	let query = '', pattern = null;
	let debounced_pattern = debounce((/*query*/) => (pattern = query ? filter_pattern(escapeHTML(query)) : null), 200);

	data.appointments.forEach(x => (delete x._content, x._content = escapeHTML(Object.values(x).join('\x00'))));

	$: debounced_pattern(query);	// argument `query` is for reactivity hinting only
</script>

<svelte:head>
	<title>Appointments</title>
</svelte:head>

<h1>Appointments</h1>
<div class="card mb-3 shadow">
	{#if data.appointments.length > 0}
		<table class="table appointments">
			<thead>
				<tr>
					<th colspan="100" style="padding: 0;">
						<div class="input-group">
							<input type="text" class="form-control" placeholder="Filter" name="q" bind:value={query} />
							{#if query}<button type="button" class="btn btn-outline-secondary" on:click={() => query = ''}>❌</button>{/if}
						</div>
					</th>
				</tr>
			</thead>
			<tbody>
				{#if pattern}
					{#each data.appointments as row}
						{#if filter_test(pattern, row._content)}
							<tr style:--bs-table-bg={strHashHSL(row.clinic, '85%')}>
								<td><div>{row.clinic}</div><div>{datetime_dtstr(new Date(row.time_scheduled))}</div></td>
								<td><div><a href="/lookup?q={encodeURIComponent(row.patient_name.charAt(0) + row.patient_last4)}&name={encodeURIComponent(row.patient_name)}&rd=true">{row.patient_name} {row.patient_last4}</a></div><div>{row.patient_phone}</div></td>
								<td class="comment">{@html filter_mark(pattern, escapeHTML(row.comment))}</td>
							</tr>
						{/if}
					{/each}
				{:else}
					{#each data.appointments as row}
						<tr style:--bs-table-bg={strHashHSL(row.clinic, '85%')}>
							<td><div>{row.clinic}</div><div>{datetime_dtstr(new Date(row.time_scheduled))}</div></td>
							<td><div><a href="/lookup?q={encodeURIComponent(row.patient_name.charAt(0) + row.patient_last4)}&name={encodeURIComponent(row.patient_name)}&rd=true">{row.patient_name} {row.patient_last4}</a></div><div>{row.patient_phone}</div></td>
							<td class="comment">{row.comment}</td>
						</tr>
					{/each}
				{/if}
			</tbody>
		</table>
	{/if}
</div>

<style>
	:global(table.appointments mark) {
		padding: 0;
		font-weight: bold;
		background-color: #fff;
	}
	.card table.table {
		margin-bottom: 0;
	}
	td.comment {
		white-space: pre-line;
	}
</style>
