<script>
	import AddTeamModal from "./AddTeamModal.svelte";
	let current_teams = [];
	import { _ } from "svelte-i18n";
	import { RunnerTeamService } from "@odit/lfk-client-js";
	const teams_promise = RunnerTeamService.runnerTeamControllerGetAll();
	import store, { users as usersstore } from "../../store.js";
	import TeamsEmptyState from "./TeamsEmptyState.svelte";
	import ConfirmTeamDeletionModal from "./ConfirmTeamDeletionModal.svelte";
	import GenerateSponsoringContracts from "../pdf_generation/GenerateSponsoringContracts.svelte";
	import GenerateRunnerCards from "../pdf_generation/GenerateRunnerCards.svelte";
	import GenerateRunnerCertificates from "../pdf_generation/GenerateRunnerCertificates.svelte";
	$: searchvalue = "";
	$: active_deletes = [];
	$: sponsoring_contracts_show = current_teams.some(
		(r) => r.is_selected === true
	);
	$: cards_show = current_teams.some((r) => r.is_selected === true);
	$: certificates_show = current_teams.some((r) => r.is_selected === true);
	$: generate_teams = current_teams.filter((r) => r.is_selected === true);
	let delete_modal_open = false;
	let modal_open = false;
	let delete_team = {};
	usersstore.subscribe((val) => {
		current_teams = val;
	});
	teams_promise.then((data) => {
		usersstore.set(data);
	});
</script>

<section class="container p-5">
	<h4 class="mb-1 text-3xl font-extrabold leading-tight">
		{$_("teams")}
	</h4>
	{#if store.state.jwtinfo.userdetails.permissions.includes("TEAM:CREATE")}
		<button
			on:click={() => {
				modal_open = true;
			}}
			type="button"
			class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:w-auto sm:text-sm"
		>
			{$_("create-team")}
		</button>
	{/if}
	<ConfirmTeamDeletionModal
		on:cancelDelete={(event) => {
			modal_open = false;
			active_deletes[event.detail.id] = false;
		}}
		bind:modal_open={delete_modal_open}
		bind:delete_team
	/>
	{#if store.state.jwtinfo.userdetails.permissions.includes("TEAM:GET")}
		{#await teams_promise}
			<div
				class="bg-teal-lightest border-t-4 border-teal rounded-b text-teal-darkest px-4 py-3 shadow-md my-2"
				role="alert"
			>
				<p class="font-bold">{$_("teams-are-being-loaded")}</p>
				<p class="text-sm">{$_("this-might-take-a-moment")}</p>
			</div>
		{:then}
			{#if current_teams.length === 0}
				<TeamsEmptyState />
			{:else}
				<input
					type="search"
					bind:value={searchvalue}
					placeholder={$_("datatable.search")}
					aria-label={$_("datatable.search")}
					class="mb-2 w-full sm:w-auto mt-1 sm:mt-0 p-2 rounded-md border"
				/>
				<GenerateSponsoringContracts
					bind:sponsoring_contracts_show
					bind:generate_teams
				/>
				<GenerateRunnerCards bind:cards_show bind:generate_teams />
				<GenerateRunnerCertificates
					bind:certificates_show
					bind:generate_teams
				/>
				<div
					class="shadow border-b border-gray-200 sm:rounded-lg overflow-x-scroll"
				>
					<table class="divide-y divide-gray-200 w-full">
						<thead class="bg-gray-50">
							<tr class="odd:bg-white even:bg-gray-100">
								<th
									scope="col"
									class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
								>
									<button
										on:click={() => {
											const newstate = !current_teams.some(
												(r) => r.is_selected === true
											);
											current_teams = current_teams.map((r) => {
												r.is_selected = newstate;
												return r;
											});
										}}
										class="underline cursor-pointer select-none"
										>{#if current_teams.some((r) => r.is_selected === true)}
											{$_("deselect-all")}
										{:else}{$_("select-all")}{/if}
									</button>
								</th>
								<th
									scope="col"
									class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
								>
									{$_("name")}
								</th>
								<th
									scope="col"
									class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
								>
									{$_("organization")}
								</th>
								<th
									scope="col"
									class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
								>
									{$_("contact")}
								</th>
								<th scope="col" class="relative px-6 py-3">
									<span class="sr-only">{$_("action")}</span>
								</th>
							</tr>
						</thead>
						<tbody class="divide-y divide-gray-200">
							{#each current_teams as t}
								{#if Object.values(t)
									.toString()
									.toLowerCase()
									.includes(searchvalue)}
									<tr
										class="odd:bg-white even:bg-gray-100"
										data-rowid="team_{t.id}"
									>
										<td class="px-6 py-4 whitespace-nowrap">
											<input
												bind:checked={t.is_selected}
												type="checkbox"
												class="focus:ring-indigo-500 size-4 text-indigo-600 border-gray-300 rounded"
											/>
										</td>
										<td class="px-6 py-4 whitespace-nowrap">
											<div class="flex items-center">
												<div class="text-sm font-medium text-gray-900">
													{t.name}
												</div>
											</div>
										</td>
										<td class="px-6 py-4 whitespace-nowrap">
											<div class="flex items-center">
												<div class="text-sm font-medium text-gray-900">
													{#if t.parentGroup}
														<a
															href="../orgs/{t.parentGroup.id}"
															class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800 border border-current"
															>{t.parentGroup.name}</a
														>
													{:else}{$_("no-organization-specified")}{/if}
												</div>
											</div>
										</td>
										<td class="px-6 py-4 whitespace-nowrap">
											<div class="flex items-center">
												<div class="text-sm font-medium text-gray-900">
													{#if t.contact}
														<a
															href="../contacts/{t.contact.id}"
															class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800 border border-current"
															>{t.contact.firstname}
															{t.contact.middlename || ""}
															{t.contact.lastname}</a
														>
													{:else}{$_("no-contact-specified")}{/if}
												</div>
											</div>
										</td>
										<td
											class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium"
										>
											<a
												href="./{t.id}"
												class="text-indigo-600 hover:text-indigo-900"
												>{$_("details")}</a
											>
											{#if store.state.jwtinfo.userdetails.permissions.includes("TEAM:DELETE")}
												<button
													on:click={() => {
														active_deletes[t.id] = true;
														delete_modal_open = true;
														delete_team = t;
													}}
													tabindex="0"
													class="ml-4 text-red-600 hover:text-red-900 cursor-pointer"
													>{$_("delete")}</button
												>
											{/if}
										</td>
									</tr>
								{/if}
							{/each}
						</tbody>
					</table>
				</div>
			{/if}
		{:catch error}
			<div
				class="text-white px-6 py-4 border-0 rounded relative mb-4 bg-red-500"
			>
				<span class="inline-block align-middle mr-8">
					<b>{$_("general_promise_error")}</b>
					{error}
				</span>
			</div>
		{/await}
	{/if}
</section>

{#if store.state.jwtinfo.userdetails.permissions.includes("TEAM:CREATE")}
	<AddTeamModal bind:current_teams bind:modal_open />
{/if}
