<script setup>
import { format, subYears } from 'date-fns';
import { ref } from 'vue';

import RangeFilter from '#/components/filters/range.vue';
import Checkbox from '#/components/form/checkbox.vue';

const props = defineProps({
	filters: {
		type: Object,
		default: null,
	},
});

// <select> doesn't work well with :value for some reason
const emit = defineEmits(['update']);

const maxDob = format(subYears(new Date(), 18), 'yyyy-MM-dd');

const dobType = ref(props.filters.dobType);
</script>

<template>
	<div class="filter">
		<div class="filter-section">
			<RangeFilter
				label="age"
				:min="18"
				:max="100"
				:value="filters.age"
				:disabled="!filters.ageRequired"
				@enable="(checked) => emit('update', 'ageRequired', checked, filters.ageRequired !== checked)"
				@input="(range) => emit('update', 'age', range, false)"
				@change="(range) => emit('update', 'age', range, true)"
			>
				<template #start><Icon icon="leaf" /></template>
				<template #end><Icon icon="tree3" /></template>
			</RangeFilter>
		</div>

		<div class="filter-section">
			<label class="filter-label">
				<span class="label">
					<Checkbox
						:checked="filters.dobRequired"
						class="checkbox"
						@change="(checked) => emit('update', 'dobRequired', checked, true)"
					/>

					<select
						v-model="dobType"
						class="input select"
						@change="(event) => { emit('update', 'dobRequired', true, false); emit('update', 'dobType', dobType, true); }"
					>
						<option value="birthday">Birthday</option>
						<option value="dob">Date of birth</option>
					</select>
				</span>
			</label>

			<div
				class="input-container"
				@click="() => emit('update', 'dobRequired', true, true)"
			>
				<input
					:value="filters.dob"
					:disabled="!filters.dobRequired"
					:max="maxDob"
					type="date"
					class="input"
					@change="(event) => emit('update', 'dob', event.target.value, true)"
				>
			</div>
		</div>
	</div>
</template>

<style scoped>
.input {
	width: 100%;
}

.select {
	flex-grow: 1;
	color: var(--glass-strong-10);

	option {
		color: var(--text);
	}
}
</style>
