<template>
	<label
		:class="[
			'es-checkbox',
			{
				'is-disabled': disabled,
			},
		]"
		@click.prevent="toggleChecked"
	>
		<span
			:class="[
				'es-checkbox__label',
				{
					'is-checked': checked,
					'is-disabled': disabled,
				},
			]"
		></span>
		<input class="es-checkbox__value" type="checkbox" :value="checked" />
		<span class="es-checkbox__name">
			<slot>
				{{ labelText }}
			</slot>
		</span>
	</label>
</template>

<script lang="ts">
import { defineComponent, ref, toRefs, watch } from 'vue'
interface IKeyConfig {
	nameKey?: string
	valueKey?: string
	disabledKey?: string
}
export default defineComponent({
	name: 'EsCheckbox',
	props: {
		modelValue: {
			type: Boolean,
			default: false,
		},
		disabled: {
			type: Boolean,
			default: false,
		},
		labelText: {
			type: String,
			default: '',
		},
	},
	emits: ['update:modelValue', 'change', 'select'],
	setup(props, ctx) {
		const { emit } = ctx
		const checked = ref(false)
		const { modelValue, disabled } = toRefs(props)
		const toggleChecked = e => {
			if (disabled.value) {
				return
			}
			const result = !modelValue.value
			emit('select', { e, data: result })
			emit('update:modelValue', result)
		}
		watch(
			modelValue,
			result => {
				checked.value = result
				emit('change', result)
			},
			{ immediate: true },
		)
		return {
			checked,
			toggleChecked,
		}
	},
})
</script>
