<script lang="ts">
	import { IconX } from '@tabler/icons-svelte-runes';
	import { OwlClient } from '$lib/owlClient';
	import { ApiTrainsTrainDetails } from '@owlboard/api-schema-types';
	import TrainServiceTable from '../TrainServiceTable.svelte';

	interface Props {
		rid: string;
		isOpen: boolean;
		onClose: () => void;
	}

	let { rid, isOpen, onClose }: Props = $props();

	let dialogElement = $state<HTMLDialogElement | null>(null);

	let trainDetail = $state<ApiTrainsTrainDetails.TrainDetailsResponse | null>(null);
	let loading = $state(true);
	let error = $state<string | null>(null);

	$effect(() => {
		if (isOpen && rid) {
			loadTrainDetails(rid);
		}
	});

	$effect(() => {
		if (!dialogElement) return;

		if (isOpen && !dialogElement.open) {
			dialogElement.showModal();
			loadTrainDetails(rid);
		} else if (!isOpen && dialogElement.open) {
			dialogElement.close();
		}
	});

	async function loadTrainDetails(rid: string) {
		loading = true;
		error = null;
		try {
			const result = await OwlClient.trains.getByRid(rid);
			trainDetail = result.data;
		} catch (err: any) {
			error = err.message || 'An error occurred fetching train details.';
		} finally {
			loading = false;
		}
	}
</script>

<dialog
	bind:this={dialogElement}
	onclose={onClose}
	onclick={(e) => {
		// Optional: close when clicking the native backdrop area outside the modal box
		const rect = dialogElement?.getBoundingClientRect();
		if (
			rect &&
			(e.clientX < rect.left ||
				e.clientX > rect.right ||
				e.clientY < rect.top ||
				e.clientY > rect.bottom)
		) {
			onClose();
		}
	}}
>
	<div class="modal-content">
		<div class="modal-header">
			<h1>
			{#if loading}
				Loading Train Detail
			{:else if error}
				Error
			{:else if trainDetail}
				{trainDetail.header.h}
			{/if}
			</h1>
			<button class="close-btn" onclick={onClose} aria-label="Close modal">
				<IconX size={20} />
			</button>
		</div>

		<div class="trainServiceModalWrapper">
			{#if loading}
				<div class="loading-state">Loading train details...</div>
			{:else if error}
				<div class="error-state">Error: {error}</div>
			{:else if trainDetail}
				<div class="scrollable-table-container">
					<TrainServiceTable {trainDetail} />
				</div>
			{/if}
		</div>
	</div>
</dialog>

<style>
	dialog {
		background: var(--color-accent);
		color: var(--color-title);
		border: none;
		border-radius: 12px;
		width: 90%;
		max-width: 400px;
		padding: 0 1.5rem 1.5rem 1.5rem;
		box-shadow: var(--shadow-std);

		opacity: 0;
		transform: scale(0.8);
		transition:
			opacity 0.3s ease,
			transform 0.5s ease,
			overlay 0.5s ease allow-discrete,
			display 0.5s ease allow-discrete;
	}

	dialog[open] {
		opacity: 1;
		transform: scale(1);
	}

	@starting-style {
		dialog[open] {
			opacity: 0;
			transform: scale(0.8);
		}
	}

	dialog::backdrop {
		background: rgba(0, 0, 0, 0);
		backdrop-filter: blur(0px);
		transition:
			background 1.15s ease,
			backdrop-filter 1.15s ease,
			overlay 1.15s ease allow-discrete,
			display 1.15s ease allow-discrete;
	}

	dialog[open]::backdrop {
		background: rgba(0, 0, 0, 0.6);
		backdrop-filter: blur(2px);
	}

	@starting-style {
		dialog[open]::backdrop {
			background: rgba(0, 0, 0, 0);
			backdrop-filter: blur(0px);
		}
	}

	.modal-content {
		position: relative;
		display: flex;
		flex-direction: column;
	}

	.modal-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-family: 'URW Gothic', sans-serif;
		margin: 0;
		padding: 0;
	}

	.close-btn {
		background: red;
		border: none;
		color: inherit;
		cursor: pointer;
		padding: 0.5rem;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		transition: background 0.2s;
	}

	.close-btn:hover {
		background: rgb(141, 0, 0);
	}

	.trainServiceModalWrapper {
		height: 75vh;
		display: flex;
		flex-direction: column;
		overflow: hidden;
		margin-top: 0;
	}

	.scrollable-table-container {
		margin-top: 0px;
		width: 100%;
		overflow-y: auto;
	}

	.loading-state,
	.error-state {
		display: flex;
		justify-content: center;
		align-items: center;
		flex: 1;
		width: 100%;
		font-weight: 500;
	}

	.error-state {
		color: var(--error-color, #ff6b6b);
	}
</style>
