<script lang="ts">
	import CheckCircleIcon from '$lib/icons/CheckCircleIcon.svelte';
	import MinusCircleIcon from '$lib/icons/MinusCircleIcon.svelte';
	import XCircleIcon from '$lib/icons/XCircleIcon.svelte';
	import type { Extension } from '@codemirror/state';
	import { githubLight } from '@fsegurai/codemirror-theme-github-light';
	import { basicSetup } from 'codemirror';
	import type { Snippet } from 'svelte';
	import CodeMirror from 'svelte-codemirror-editor';

	interface Props {
		title: string;
		value: string;
		placeholder?: string;
		readonly?: boolean;
		children?: Snippet;
		headerActions?: Snippet;
		subtitle?: string;
		error?: string;
		status?: 'success' | 'error' | 'indeterminate';
		timing?: number;
		pillText?: string;
		langExtension?: Extension;
	}

	let {
		title,
		error,
		value = $bindable(),
		placeholder = '',
		readonly = false,
		children,
		headerActions,
		subtitle,
		status,
		timing,
		pillText,
		langExtension
	}: Props = $props();
</script>

<div class="relative flex flex-1 flex-col overflow-hidden border-r border-gray-200 last:border-r-0">
	<div class="flex items-center border-b border-gray-200 bg-gray-50/50 px-4 py-3">
		{#if status === 'success'}
			<CheckCircleIcon class="mr-2 h-5 w-5 text-green-500" />
		{:else if status === 'error'}
			<XCircleIcon class="mr-2 h-5 w-5 text-red-500" />
		{:else if status === 'indeterminate'}
			<MinusCircleIcon class="mr-2 h-5 w-5 text-gray-400" />
		{/if}
		<div class="flex-1">
			<h2 class="flex items-center text-sm font-semibold tracking-wide text-gray-900 uppercase">
				{title}
				{#if pillText}
					<span
						class="ml-2 inline-flex items-center rounded-full bg-blue-100 px-2 py-0.5 text-xs font-medium text-blue-800"
					>
						{pillText}
					</span>
				{/if}
			</h2>
			{#if subtitle}
				<p class="text-xs text-gray-500">{subtitle}</p>
			{/if}
		</div>
		{#if headerActions}
			<div class="ml-4">
				{@render headerActions()}
			</div>
		{/if}
		{#if timing !== undefined}
			<div class="ml-4 text-xs text-gray-500">{timing}ms</div>
		{/if}
	</div>

	{#if error}
		<div class="border-b border-gray-200 bg-red-300 p-4 text-xs">
			<pre>{error}</pre>
		</div>
	{/if}

	<CodeMirror
		bind:value
		extensions={[basicSetup, langExtension].filter(Boolean) as Extension[]}
		theme={githubLight}
		{placeholder}
		{readonly}
		class="text-sm"
	/>

	{#if children}
		{@render children()}
	{/if}
</div>
