<script setup lang="ts">
import Toast from "toasters";
import { defineAsyncComponent, ref, onMounted } from "vue";
import { GenericResponse } from "@musare_types/actions/GenericActions";
import { useForm } from "@/composables/useForm";
import { useWebsocketsStore } from "@/stores/websockets";
import { useModalsStore } from "@/stores/modals";

const Modal = defineAsyncComponent(() => import("@/components/Modal.vue"));
const SaveButton = defineAsyncComponent(
	() => import("@/components/SaveButton.vue")
);

const props = defineProps({
	modalUuid: { type: String, required: true },
	createArtist: { type: Boolean, default: false },
	artistId: { type: String, default: null },
	sector: { type: String, default: "admin" }
});

const { socket } = useWebsocketsStore();

const { closeCurrentModal } = useModalsStore();

const createdBy = ref();
const createdAt = ref(0);

const { inputs, save, setOriginalValue } = useForm(
	{
		name: {
			value: ""
		},
		musicbrainzIdentifier: {
			value: ""
		}
	},
	({ status, messages, values }, resolve, reject) => {
		if (status === "success") {
			const data = {
				name: values.name,
				musicbrainzIdentifier: values.musicbrainzIdentifier
			};
			const cb = (res: GenericResponse) => {
				new Toast(res.message);
				if (res.status === "success") resolve();
				else reject(new Error(res.message));
			};
			if (props.createArtist) socket.dispatch("artists.create", data, cb);
			else socket.dispatch("artists.update", props.artistId, data, cb);
		} else {
			if (status === "unchanged") new Toast(messages.unchanged);
			else if (status === "error")
				Object.values(messages).forEach(message => {
					new Toast({ content: message, timeout: 8000 });
				});
			resolve();
		}
	},
	{
		modalUuid: props.modalUuid
	}
);

onMounted(() => {
	socket.onConnect(() => {
		if (props.artistId && !props.createArtist) {
			socket.dispatch(`artists.getArtistFromId`, props.artistId, res => {
				// res: GetArtistResponse
				if (res.status === "success") {
					setOriginalValue({
						name: res.data.artist.name,
						musicbrainzIdentifier:
							res.data.artist.musicbrainzIdentifier
					});
					createdBy.value = res.data.artist.createdBy;
					createdAt.value = res.data.artist.createdAt;
				} else {
					new Toast("Artist with that ID not found.");
					closeCurrentModal();
				}
			});
		}
	});
});

const saveArtist = (close?: boolean) => {
	save(() => {
		if (close) {
			closeCurrentModal();
		}
	});
};
</script>

<template>
	<modal
		class="edit-artist-modal"
		:title="createArtist ? 'Create Artist' : 'Edit Artist'"
		:size="'wide'"
		:split="true"
	>
		<template #body>
			<div class="control is-grouped">
				<div class="name-container">
					<label class="label">Name</label>
					<p class="control has-addons">
						<input
							class="input"
							type="text"
							:ref="el => (inputs['name'].ref = el)"
							v-model="inputs['name'].value"
							placeholder="Enter artist name..."
						/>
					</p>
				</div>
			</div>
			<div class="control is-grouped">
				<div class="musicbrainz-identifier-container">
					<label class="label">MusicBrainz identifier</label>
					<p class="control has-addons">
						<input
							class="input"
							type="text"
							:ref="
								el => (inputs['musicbrainzIdentifier'].ref = el)
							"
							v-model="inputs['musicbrainzIdentifier'].value"
							placeholder="Enter MusicBrainz identifier..."
						/>
					</p>
				</div>
			</div>
			<div>
				<p>MusicBrainz data</p>
			</div>
		</template>
		<template #footer>
			<div>
				<save-button
					:default-message="`${createArtist ? 'Create' : 'Update'} Artist`"
					@clicked="saveArtist()"
				/>
				<save-button
					:default-message="`${createArtist ? 'Create' : 'Update'} and close`"
					@clicked="saveArtist(true)"
				/>
			</div>
		</template>
	</modal>
</template>

<style lang="less"></style>

<style lang="less" scoped></style>
