<script lang="ts">
	import { getContext } from 'svelte'
	import { twMerge } from 'tailwind-merge'
	import { initOutput } from '../../editor/appUtils'
	import type { AppViewerContext, ComponentCustomCSS, RichConfigurations } from '../../types'
	import { concatCustomCss } from '../../utils'
	import AlignWrapper from '../helpers/AlignWrapper.svelte'
	import InputValue from '../helpers/InputValue.svelte'
	import InitializeComponent from '../helpers/InitializeComponent.svelte'

	export let id: string
	export let configuration: RichConfigurations
	export let inputType: 'date'
	export let verticalAlignment: 'top' | 'center' | 'bottom' | undefined = undefined
	export let customCss: ComponentCustomCSS<'dateinputcomponent'> | undefined = undefined
	export let render: boolean

	const { app, worldStore, selectedComponent, componentControl } =
		getContext<AppViewerContext>('AppViewerContext')
	let labelValue: string = 'Title'
	let minValue: string = ''
	let maxValue: string = ''
	let defaultValue: string | undefined = undefined
	let format: string | undefined = undefined

	let value: string | undefined = undefined

	$componentControl[id] = {
		setValue(nvalue: string) {
			value = nvalue
		}
	}

	let outputs = initOutput($worldStore, id, {
		result: undefined as string | undefined
	})

	$: handleDefault(defaultValue)

	function formatDate(dateString: string, format: string = 'DD.MM.YYYY') {
		const date = new Date(dateString)

		if (format === '') {
			format = 'DD.MM.YYYY'
		}

		const padZero = (num: number) => (num < 10 ? '0' + num : num.toString())

		const formatTokens = {
			YYYY: date.getFullYear(),
			MM: padZero(date.getMonth() + 1),
			DD: padZero(date.getDate()),
			hh: padZero(date.getHours()),
			mm: padZero(date.getMinutes()),
			ss: padZero(date.getSeconds())
		}

		return format.replace(/YYYY|MM|DD|hh|mm|ss/g, (match) => formatTokens[match])
	}

	$: value && outputs?.result.set(formatDate(value, format))

	function handleDefault(defaultValue: string | undefined) {
		value = defaultValue
	}
	$: css = concatCustomCss($app.css?.dateinputcomponent, customCss)
</script>

<InputValue {id} input={configuration.label} bind:value={labelValue} />
<InputValue {id} input={configuration.minDate} bind:value={minValue} />
<InputValue {id} input={configuration.maxDate} bind:value={maxValue} />
<InputValue {id} input={configuration.defaultValue} bind:value={defaultValue} />
<InputValue {id} input={configuration.outputFormat} bind:value={format} />

<InitializeComponent {id} />

<AlignWrapper {render} {verticalAlignment}>
	{#if inputType === 'date'}
		<input
			on:focus={() => ($selectedComponent = [id])}
			on:pointerdown|stopPropagation
			type="date"
			bind:value
			min={minValue}
			max={maxValue}
			placeholder="Type..."
			class={twMerge(css?.input?.class ?? '')}
			style={css?.input?.style ?? ''}
		/>
	{/if}
</AlignWrapper>
