<script>
	import {
		RunnerOrganizationService,
		RunnerService,
		RunnerTeamService,
	} from "@odit/lfk-client-js";
	import {
		createSvelteTable,
		flexRender,
		getCoreRowModel,
		getFilteredRowModel,
		getPaginationRowModel,
		getSortedRowModel,
		renderComponent,
	} from "@tanstack/svelte-table";
	import { onMount } from "svelte";
	import { writable } from "svelte/store";
	import GenerateRunnerCards from "../pdf_generation/GenerateRunnerCards.svelte";
	import GenerateRunnerCertificates from "../pdf_generation/GenerateRunnerCertificates.svelte";
	import GenerateSponsoringContracts from "../pdf_generation/GenerateSponsoringContracts.svelte";
	import InputElement from "../shared/InputElement.svelte";
	import TableActions from "../shared/TableActions.svelte";
	import { groupFilter } from "../shared/tablefilters";
	import DeleteRunnerModal from "./DeleteRunnerModal.svelte";
	import TableBottom from "../shared/TableBottom.svelte";
	import TableHeader from "../shared/TableHeader.svelte";

	$: selectedRunners =
		$table?.getSelectedRowModel().rows.map((row) => row.original) || [];
	$: selected =
		$table?.getSelectedRowModel().rows.map((row) => row.index) || [];

	$: active_delete = undefined;
	let dataLoaded = false;
	export let current_runners = [];
	$: sponsoring_contracts_show = selected.length > 0;
	$: cards_show = selected.length > 0;
	$: certificates_show = selected.length > 0;
	$: teams = [];
	$: orgs = [];

	export const addRunners = (runners) => {
		current_runners = current_runners.concat(...runners);
		options.update((options) => ({
			...options,
			data: current_runners,
		}));
	};

	//Section table
	const columns = [
		{
			accessorKey: "id",
			header: () => "id",
			filterFn: `equalsString`,
		},
		{
			accessorKey: "firstname",
			header: () => $_("first-name"),
			filterFn: `includesString`,
		},
		{
			accessorKey: "middlename",
			header: () => $_("middle-name"),
			cell: (info) => {
				if (!info || !info.getValue()) {
					return "";
				}
				return info.getValue();
			},
			filterFn: `includesString`,
		},
		{
			accessorKey: "lastname",
			header: () => $_("last-name"),
			filterFn: `includesString`,
		},
		{
			accessorKey: "group",
			header: () => $_("group"),
			cell: (info) => {
				const group = info.getValue();
				if (group.responseType === "RUNNERORGANIZATION") {
					return group.name;
				}
				return `${group.parentGroup.name} > ${group.name}`;
			},
			filterFn: `group`,
		},
		{
			accessorKey: "distance",
			header: () => $_("distance"),
			cell: (info) => {
				if (info.getValue() < 1000) {
					return `${info.getValue()} m`;
				}
				return `${(info.getValue() / 1000).toFixed(1)} km`;
			},
			enableColumnFilter: false,
		},
		{
			accessorKey: "actions",
			header: () => $_("action"),
			cell: (info) => {
				return renderComponent(TableActions, {
					detailsLink: `./${info.row.original.id}`,
					deleteAction: () => {
						active_delete =
							current_runners[
								current_runners.findIndex((r) => r.id == info.row.original.id)
							];
					},
					deleteEnabled:
						store.state.jwtinfo.userdetails.permissions.includes(
							"RUNNER:DELETE"
						),
				});
			},
			enableColumnFilter: false,
			enableSorting: false,
		},
	];
	const options = writable({
		data: [],
		columns: columns,
		filterFns: {
			group: groupFilter,
		},
		initialState: {
			pagination: {
				pageSize: 50,
			},
		},
		enableRowSelection: true,
		getCoreRowModel: getCoreRowModel(),
		getFilteredRowModel: getFilteredRowModel(),
		getPaginationRowModel: getPaginationRowModel(),
		getSortedRowModel: getSortedRowModel(),
	});
	const table = createSvelteTable(options);

	async function deleteRunner(delete_runner_id) {
		await RunnerService.runnerControllerRemove(delete_runner_id, true);
		current_runners = current_runners.filter((r) => r.id !== delete_runner_id);
		options.update((options) => ({
			...options,
			data: current_runners,
		}));
		toast.success($_("runner-deleted"));
	}

	onMount(async () => {
		RunnerTeamService.runnerTeamControllerGetAll().then((val) => {
			teams = val;
		});
		RunnerOrganizationService.runnerOrganizationControllerGetAll().then(
			(val) => {
				orgs = val;
			}
		);

		let page = 0;
		while (page >= 0) {
			const runners = await RunnerService.runnerControllerGetAll(page, 500);
			if (runners.length == 0) {
				page = -2;
			}

			current_runners = current_runners.concat(...runners);
			options.update((options) => ({
				...options,
				data: current_runners,
			}));

			dataLoaded = true;
			page++;
		}
	});
	import { _ } from "svelte-i18n";
	import store from "../../store";
	import AddRunnerModal from "./AddRunnerModal.svelte";
	import ImportRunnerModal from "./ImportRunnerModal.svelte";
	import toast from "svelte-french-toast";
	$: current_runners = [];
	export let modal_open = false;
	export let import_modal_open = false;
</script>

<section class="container p-5">
	<h4 class="mb-1 text-3xl font-extrabold leading-tight">
		{$_("runners")}
	</h4>
	{#if store.state.jwtinfo.userdetails.permissions.includes("RUNNER: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 mb-1 lg:mb-0"
		>
			{$_("laeufer-hinzufuegen")}
		</button>
		<button
			on:click={() => {
				import_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 mb-1 lg:mb-0"
		>
			{$_("import-runners")}
		</button>
	{/if}
	<DeleteRunnerModal
		delete_runner={active_delete}
		modal_open={active_delete != undefined}
		on:delete={(event) => {
			deleteRunner(event.detail.id);
		}}
	/>
	{#if store.state.jwtinfo.userdetails.permissions.includes("RUNNER:GET")}
		{#if !dataLoaded}
			<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">{$_("runners-are-being-loaded")}</p>
				<p class="text-sm">{$_("this-might-take-a-moment")}</p>
			</div>
		{:else}
			<GenerateSponsoringContracts
				bind:sponsoring_contracts_show
				bind:generate_runners={selectedRunners}
			/>
			<GenerateRunnerCards
				bind:cards_show
				bind:generate_runners={selectedRunners}
			/>
			<GenerateRunnerCertificates
				bind:certificates_show
				bind:generate_runners={selectedRunners}
			/>
			<div class="overflow-x-auto">
				<table class="w-full">
					<thead class="border-b border-gray-400">
						{#each $table.getHeaderGroups() as headerGroup}
							<tr class="select-none">
								<th class="inset-y-0 left-0 px-4 py-2 text-left w-px">
									<InputElement
										type="checkbox"
										checked={$table.getIsAllRowsSelected()}
										indeterminate={$table.getIsSomeRowsSelected()}
										on:change={() => $table.toggleAllRowsSelected()}
									/>
								</th>
								{#each headerGroup.headers as header}
									<TableHeader {header} />
								{/each}
							</tr>
						{/each}
					</thead>
					<tbody>
						{#each $table.getRowModel().rows as row}
							<tr class="odd:bg-white even:bg-gray-100">
								<td class="inset-y-0 left-0 px-4 py-2 text-center w-px">
									<InputElement
										type="checkbox"
										checked={row.getIsSelected()}
										on:change={() => row.toggleSelected()}
									/>
								</td>
								{#each row.getVisibleCells() as cell}
									<td>
										<svelte:component
											this={flexRender(
												cell.column.columnDef.cell,
												cell.getContext()
											)}
										/>
									</td>
								{/each}
							</tr>
						{/each}
					</tbody>
				</table>
			</div>
			<div class="h-2" />
		{/if}
	{/if}
	<TableBottom {table} {selected} />
</section>

{#if store.state.jwtinfo.userdetails.permissions.includes("RUNNER:CREATE")}
	<AddRunnerModal
		bind:modal_open
		on:created={(event) => {
			addRunners(event.detail.runners);
		}}
	/>
	<ImportRunnerModal
		on:cancelDelete={(event) => {
			import_modal_open = false;
		}}
		passed_team={{}}
		passed_orgs={[]}
		passed_org={{}}
		opened_from="RunnerOverview"
		bind:import_modal_open
		on:created={(event) => {
			addRunners(event.detail.runners);
		}}
	/>
{/if}

<style>
	table tbody tr td:nth-child(2) {
		font-family: monospace;
	}
</style>
