<script lang="ts">
	import { page } from '$app/stores';
	import { goto } from '$app/navigation';
	import PartForm from '$lib/components/dashboard/goods/parts/partForm.svelte';
	import PrerequisitesModal from '$lib/components/dashboard/PrerequisitesModal.svelte';
	import { currentUser } from '$lib/auth';
	import {
		canCreateGoodsParts,
		canEditGoodsParts
	} from '$lib/permissions/goods-parts-permissions';
	import ErrorState from '$lib/components/dashboard/common/error-state.svelte';

	let routeId = $derived($page.params.id);
	let id = $derived($page.params.id === 'new' ? null : Number($page.params.id));
	let isEditingPart = $derived(!!routeId && routeId !== 'new');
	const canAccessPartEditor = $derived(
		isEditingPart ? canEditGoodsParts($currentUser) : canCreateGoodsParts($currentUser)
	);
	let type = $state<'inv' | 'fa' | 'both'>('fa');

	// When editing, the PartForm auto-detects the type from the loaded data.
	// When creating, the user picks the type here.

	let { data }: { data: { agentsCount?: number; clientsCount?: number; isCreate?: boolean } } =
		$props();

	let showPrerequisitesModal = $state(false);
	let hasTriedToShowPrerequisitesModal = $state(false);
	$effect(() => {
		if (hasTriedToShowPrerequisitesModal) return;
		if (!data?.isCreate) return;
		const agentsCount = data.agentsCount ?? 0;
		const clientsCount = data.clientsCount ?? 0;
		if (agentsCount === 0 || clientsCount === 0) {
			hasTriedToShowPrerequisitesModal = true;
			showPrerequisitesModal = true;
		}
	});
</script>

{#if !canAccessPartEditor}
	<div
		class="flex h-[calc(100svh-4rem)] flex-col p-6 group-has-data-[collapsible=icon]/sidebar-wrapper:h-[calc(100svh-3rem)]"
	>
		<ErrorState status={403} />
	</div>
{:else}
{#if data?.isCreate}
	<PrerequisitesModal
		bind:open={showPrerequisitesModal}
		agentsCount={data?.agentsCount ?? 0}
		clientsCount={data?.clientsCount ?? 0}
		onAccept={() => (showPrerequisitesModal = false)}
		onCancel={() => goto('/dashboard/goods/parts')}
	/>
{/if}

<div class="space-y-4 p-4">
	<PartForm partId={id} bind:formType={type} />
</div>
{/if}
