<script setup>
import { ref, watch } from 'vue';

import MovieSearch from '#/components/movies/search.vue';

const props = defineProps({
	item: {
		type: Object,
		default: null,
	},
	scene: {
		type: Object,
		default: null,
	},
	edits: {
		type: Object,
		default: () => {},
	},
	editing: {
		type: Set,
		default: null,
	},
});

const emit = defineEmits(['movies']);

const newMovies = ref([]);

function addMovie(movie) {
	newMovies.value = newMovies.value.concat(movie);

	console.log(movie);

	emit('movies', props.edits.movies.concat(movie.id));

	console.log(props.edits);
}

watch(() => props.scene, () => {
	newMovies.value = [];
});
</script>

<template>
	<ul
		class="movies nolist"
		:class="{ disabled: !editing.has(item.key) }"
	>
		<li
			v-for="movie in [...item.value, ...newMovies]"
			:key="`movie-${movie.id}`"
			class="movie"
			:class="{ deleted: edits.movies && !edits.movies.some((movieId) => movieId === movie.id) }"
		>
			<span class="movie-name">{{ movie.title }}</span>

			<Icon
				v-if="edits.movies && !edits.movies.some((movieId) => movieId === movie.id)"
				icon="checkmark"
				class="add"
				@click="emit('movies', edits.movies.concat(movie.id))"
			/>

			<Icon
				v-else
				icon="cross2"
				class="remove"
				@click="emit('movies', edits.movies.filter((movieId) => movieId !== movie.id))"
			/>
		</li>

		<li class="new">
			<MovieSearch
				:disabled="!editing.has(item.key)"
				@movie="addMovie"
			>
				<Icon
					icon="plus3"
					class="add"
				/>
			</MovieSearch>
		</li>
	</ul>
</template>

<style scoped>
.movies {
	display: flex;
	flex-wrap: wrap;
	gap: .35rem .25rem;

	&.disabled {
		.movie {
			background: var(--glass-weak-50);
			color: var(--glass-strong-10);

			.remove,
			.add {
				fill: var(--shadow-weak-30);
				background: var(--shadow-weak-50);
			}
		}

		.new .icon {
			background: var(--shadow-weak-40);
		}
	}

	.new {
		display: flex;
		align-items: center;
		margin-left: .25rem;

		&:hover {
			box-shadow: 0 0 3px var(--shadow-weak-20);
		}

		.icon {
			height: 100%;
			padding: 0 .5rem;
			background: var(--success);
			fill: var(--text-light);
		}
	}
}

.movie {
	display: flex;
	align-items: stretch;
	border-radius: .25rem;
	background: var(--background);
	box-shadow: 0 0 3px var(--shadow-weak-30);

	&.deleted  {
		color: var(--glass);
		text-decoration: line-through;
	}
}

.movie,
.new {
	.remove,
	.add {
		height: auto;
		padding: .25rem .3rem;
		border-radius: .25rem;
		fill: var(--highlight-strong-10);

		&:hover {
			fill: var(--text-light);
			cursor: pointer;
		}
	}

	.remove {
		fill: var(--error);

		&:hover {
			background: var(--error);
		}
	}

	.add {
		fill: var(--success);

		&:hover {
			background: var(--success);
		}
	}
}

.movie-name {
	padding: .25rem .5rem;
}
</style>
