<script lang="ts">
	type Assignee = { id: string; userId: string; user: { id: string; name: string; email?: string; avatarUrl: string | null } };
	type Member = { id: string; userId: string; role: string; user: { id: string; name: string; email?: string; avatarUrl: string | null } };

	type Props = {
		cardId: string;
		boardId: string;
		columnId: string | undefined;
		currentAssignees: Assignee[];
		boardMembers: Member[];
		canEdit: boolean;
		onupdate: (assignees: Assignee[]) => void;
	};

	let { cardId, boardId, columnId, currentAssignees, boardMembers, canEdit, onupdate }: Props = $props();

	let showDropdown = $state(false);

	function isAssigned(userId: string): boolean {
		return currentAssignees.some((a) => a.userId === userId);
	}

	async function toggleAssignee(member: Member) {
		const base = `/api/boards/${boardId}/columns/${columnId}/cards/${cardId}/assignees`;
		if (isAssigned(member.userId)) {
			const res = await fetch(base, {
				method: 'DELETE',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({ userId: member.userId })
			});
			if (res.ok) {
				onupdate(currentAssignees.filter((a) => a.userId !== member.userId));
			}
		} else {
			const res = await fetch(base, {
				method: 'POST',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({ userId: member.userId })
			});
			if (res.ok) {
				const data = await res.json();
				onupdate([...currentAssignees, data.assignee]);
			}
		}
	}

	async function removeAssignee(userId: string) {
		const base = `/api/boards/${boardId}/columns/${columnId}/cards/${cardId}/assignees`;
		const res = await fetch(base, {
			method: 'DELETE',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify({ userId })
		});
		if (res.ok) {
			onupdate(currentAssignees.filter((a) => a.userId !== userId));
		}
	}
</script>

<div>
	<h3 class="text-xs font-semibold text-gray-500 uppercase mb-2">Assignees</h3>
	<div class="flex flex-wrap gap-1.5">
		{#each currentAssignees as assignee}
			<div class="flex items-center gap-1 rounded-full bg-gray-100 pl-1 pr-2 py-0.5">
				<div class="w-5 h-5 rounded-full bg-[var(--color-primary)] text-white text-[10px] flex items-center justify-center">
					{assignee.user.name[0].toUpperCase()}
				</div>
				<span class="text-xs text-gray-700">{assignee.user.name}</span>
				{#if canEdit}
					<button onclick={() => removeAssignee(assignee.userId)} class="text-gray-400 hover:text-red-500 ml-0.5">
						<svg class="w-3 h-3" viewBox="0 0 20 20" fill="currentColor">
							<path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" />
						</svg>
					</button>
				{/if}
			</div>
		{/each}
		{#if canEdit}
			<div class="relative">
				<button
					onclick={() => (showDropdown = !showDropdown)}
					class="inline-flex items-center rounded-full bg-gray-100 w-6 h-6 text-xs text-gray-500 hover:bg-gray-200 justify-center"
				>
					+
				</button>
				{#if showDropdown}
					<!-- svelte-ignore a11y_click_events_have_key_events a11y_no_static_element_interactions -->
					<div class="fixed inset-0 z-10" onclick={() => (showDropdown = false)}></div>
					<div class="absolute right-0 top-full mt-1 z-20 w-52 rounded-lg bg-white shadow-lg border border-gray-200 p-1">
						<div class="max-h-48 overflow-y-auto">
							{#each boardMembers as member}
								<button
									onclick={() => toggleAssignee(member)}
									class="w-full flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-gray-50 {isAssigned(member.userId) ? 'bg-blue-50' : ''}"
								>
									<div class="w-6 h-6 rounded-full bg-[var(--color-primary)] text-white text-xs flex items-center justify-center">
										{member.user.name[0].toUpperCase()}
									</div>
									<span class="flex-1 text-left">{member.user.name}</span>
									{#if isAssigned(member.userId)}
										<svg class="w-4 h-4 text-blue-500" viewBox="0 0 20 20" fill="currentColor">
											<path fill-rule="evenodd" d="M16.704 4.153a.75.75 0 01.143 1.052l-8 10.5a.75.75 0 01-1.127.075l-4.5-4.5a.75.75 0 011.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 011.05-.143z" clip-rule="evenodd" />
										</svg>
									{/if}
								</button>
							{/each}
						</div>
					</div>
				{/if}
			</div>
		{/if}
	</div>
</div>
