<template>
	<div
		class="elevation-2 rounded-lg mt-3 d-block"
		:class="
			validationPayment
				? 'border-error-stripe'
				: ''
		"
	>
		<v-card-title class="border-b">Payment</v-card-title>

		<v-radio-group v-model="valueRadio" :disabled="lean.response.data.payment_methods.length === 0">
			<v-radio label="Use a saved payment method" value="cards"></v-radio>
		</v-radio-group>

		<v-progress-circular
			v-if="lean.loading"
			:size="50"
			class="my-5 mx-auto d-block"
			indeterminate
		/>
		<template v-if="valueRadio === 'cards'">
			<v-row align="start" align-content="start" class="mx-3">
				<MethodPayment
					v-for="(m, i) in lean.response.data.payment_methods || []"
					:key="m.id"
					:active="
						props.modelValue ? props.modelValue.id === m.id : false
					"
					:model-value="m"
					@removedPaymentMethod="
						(method) => filterPaymentMethod(method)
					"
					@update:modelValue="emitModelValue($event, false)"
				/>
			</v-row>
		</template>

		<v-radio-group v-model="valueRadio" @click="removeCardSelect">
			<v-radio label="Choose another payment method" value="new-card"></v-radio>
		</v-radio-group>

		<div class="pa-5" v-if="valueRadio === 'new-card'" @click="emitModelValue(null, false)">
			<StripeCard :card-selected="props.modelValue?.id" :hide-details="true"/>
			<v-checkbox
				:model-value="props.paymentData?.bookings ? props.paymentData.bookings.save_card : props.paymentData.save_card"
				label="Save this card"
				:value="1"
			/>
		</div>
	</div>

	<span
		v-if="
			Object.values(props.modelValue ?? {}).length === 0 &&
			validationPayment
		"
		class="text-red pl-2 my-3 d-block"
	>
		This field is required
	</span>
</template>

<script setup>
const MethodPayment = Vue.defineAsyncComponent(
	async () =>
		await loadModule(
			`${SAS_URL}/src/components/payment/Method.vue`,
			options
		)
);

const StripeCard = Vue.defineAsyncComponent(
	async () =>
		await loadModule(
			`${SAS_URL}/src/components/payment/StripeCard.vue`,
			options
		)
);

const props = defineProps({
	modelValue: {type: Object, default: {}},
	paymentData: {type: Object, default: {}},
	validationPayment: {type: Boolean, default: false},
});
const emit = defineEmits(["update:modelValue", "update:newCard", "stepLogin"]);
const store = useStripeStore()
const {valueRadio, paymentMethod} = Pinia.storeToRefs(store)

Vue.watch(() => paymentMethod.value, (value) => {
	const newCard = props.paymentData.bookings.save_card
	emitModelValue(value, newCard)

	valueRadio.value = 'cards'
}, {deep: true})

const emitModelValue = (value, newCard = false) => {
	const findCard = lean.response.data.payment_methods.find(card => card.id === value.id);
	if (newCard && !findCard) {
		lean.response.data.payment_methods.push(value); 
	}

	if (typeof value === "object" && value !== null) {
		value._id = value.id;
		value.id = value.stripe_payment_method_id;
	}
	emit("update:modelValue", value);
	// emit("update:newCard", newCard);
};

const lean = useAxios({
	url: "/guest/lineup_payment_methods",
	method: "get",
	headers: {SearchAndStayApiToken: "null"},
	autoSubmit: true,
	response: {data: {payment_methods: []}},
	onSuccess(r) {
		if (r.data.data.payment_methods.length > 0) {
			valueRadio.value = 'cards'
			const card = r.data.data.payment_methods[0]
			card._id = card.id;
			card.id = card.stripe_payment_method_id;
			emit("update:modelValue", card);
		} else {
			valueRadio.value = 'new-card'
		}
	},
	onError(err) {
		if (err.status === 404) {
			valueRadio.value = 'new-card'
		}

		if (err.data.errors.status === 409) {
			emit("stepLogin", err.data.errors);
		}
	},
});

const filterPaymentMethod = (method) => {
	lean.response.data.payment_methods = method.payment_methods;
};

const removeCardSelect = () => {
	emit("update:modelValue", {});
}
</script>

<style scoped>
.border-error-stripe {
	border: 1px solid red;
}
</style>
