<script lang="ts">
	import { Modal, Button, Alert, Icon, Input, Label } from '@sveltestrap/sveltestrap';
	import { scenariosApi } from '$api';
	import { DEFAULT_SCENARIO, type FlightParameters, type SavedScenario } from '$domain';
	import { addToast } from '$ui';
	import { t } from '$i18n';

	interface Props {
		isOpen?: boolean;
		onSaved?: (s: SavedScenario) => void;
	}

	let { isOpen = $bindable(false), onSaved = (_: SavedScenario) => {} }: Props = $props();

	let draft = $state<SavedScenario>({ ...DEFAULT_SCENARIO, id: 0 });
	let alertText = $state('');

	export function openCreate(flightParameters: FlightParameters) {
		draft = {
			...DEFAULT_SCENARIO,
			id: 0,
			name: '',
			flight_parameters: flightParameters,
		};
		alertText = '';
		isOpen = true;
	}

	export function openEdit(scenario: SavedScenario) {
		draft = { ...scenario };
		alertText = '';
		isOpen = true;
	}

	function close() {
		isOpen = false;
	}

	async function handleSave() {
		try {
			const saved =
				draft.id && draft.id > 0
					? await scenariosApi.update(draft)
					: await scenariosApi.create(draft);
			addToast({ header: $t('scenario.updated'), body: saved.name, color: 'success' });
			onSaved(saved);
			close();
		} catch (err: unknown) {
			alertText = (err as Error).message;
		}
	}
</script>

<Modal {isOpen} toggle={close} size="lg" fade={false} scrollable>
	<div class="modal-header">
		<h5 class="modal-title">{$t('scenario.title')}</h5>
		<button type="button" class="btn-close" onclick={close} aria-label="Close"></button>
	</div>
	<div class="modal-body">
		{#if alertText}
			<Alert color="danger" isOpen={true} toggle={() => (alertText = '')} fade={false}>
				<Icon name="exclamation-triangle" class="me-2" />
				{alertText}
			</Alert>
		{/if}
		<form
			onsubmit={(e) => {
				e.preventDefault();
				handleSave();
			}}>
			<div class="mb-2">
				<Label class="small">{$t('scenario.select')}</Label>
				<Input class="form-control-sm" type="text" bind:value={draft.name} required />
			</div>
			<div class="d-flex gap-2">
				<Button type="submit" color="success" size="sm">{$t('editor.save')}</Button>
				<Button color="secondary" size="sm" type="button" onclick={close}>
					{$t('editor.close')}
				</Button>
			</div>
		</form>
	</div>
</Modal>
