<script setup lang="ts" generic="ContextObjType extends { [key: string]: any }">
import { Btn } from '@bagelink/vue'

export interface RadioOption<T> {
	imgAlt?: string
	imgSrc?: string
	subLabel?: string
	label?: string
	id?: string
	contextObj?: T
	value: any
}

const props = defineProps<{
	id?: string
	groupName?: string
	options: RadioOption<ContextObjType>[]
	deletable?: boolean
	required?: boolean
	error?: string
	disabled?: boolean
}>()

const emit = defineEmits(['delete', 'focus', 'blur', 'change'])

const name = $computed(
	() => (
		props.groupName
		|| props.id
		|| Math.random().toString(36).substring(2, 15)
	)
)
const selectedOption = defineModel('modelValue')
let isFocused = $ref(false)

const containerClasses = $computed(() => ({
	'has-error': !!props.error,
	'is-disabled': props.disabled,
	'is-focused': isFocused
}))

function handleFocus() {
	isFocused = true
	emit('focus')
}

function handleBlur() {
	isFocused = false
	emit('blur')
}

function handleChange() {
	emit('change', selectedOption.value)
}
</script>

<template>
	<div :class="containerClasses">
		<label
			v-for="(opt, index) in options"
			:key="opt.id || `${name}-${index}`"
			class="border rounded p-1 flex bg-gray-light mb-05 gap-075 active-list-item hover"
			:for="opt.id || `${name}-${index}`"
		>
			<input
				:id="opt.id || `${name}-${index}`"
				v-model="selectedOption"
				:disabled
				class="radio-input-list"
				type="radio"
				:name
				:value="opt.value"
				:required="required"
				@focus="handleFocus"
				@blur="handleBlur"
				@change="handleChange"
			>
			<div class="flex w-100 gap-1 flex-wrap m_gap-05 m_gap-row-025">
				<img
					v-if="opt.imgSrc"
					class="bg-popup shadow-light py-025 radius-05 m_w40"
					width="60"
					:src="opt.imgSrc"
					:alt="opt.imgAlt"
				>
				<div class="">
					<p v-if="opt.label" class="m-0 m_txt-14">{{ opt.label }}</p>
					<p v-if="opt.subLabel" class="txt-gray txt-12 m-0">{{ opt.subLabel }}</p>
				</div>
				<slot name="radioItem" v-bind="opt" />
			</div>
			<Btn
				v-if="deletable"
				class="ms-auto"
				flat thin icon="delete"
				@click="$emit('delete', opt)"
			/>
		</label>
	</div>
</template>

<style scoped>
.radio-input-list{
	width: auto;
	transform: scale(1.4);
	margin-inline-end: 0.6rem;

}
.active-list-item:has(:checked){
	background: var(--bgl-primary-light) !important;
	border-color: var(--bgl-primary) !important;
	accent-color: var(--bgl-accent-color);
}

.has-error .active-list-item {
	border-color: var(--bgl-red) !important;
}

.has-error :is(input[type="radio"]) {
	accent-color: var(--bgl-red);
}
</style>
