<script lang="ts">
	import { goto } from '$app/navigation';
	import { resolve } from '$app/paths';
	import { page } from '$app/state';
	import { Field as FormField, Control, FieldErrors } from 'formsnap';
	import FormSelect from '$lib/components/form-select.svelte';
	import { industryLabel, industryOptions } from '$lib/constants/industries';
	import * as Field from '$lib/components/ui/field/index.js';
	import { toast } from 'svelte-sonner';
	import { superForm } from 'sveltekit-superforms';
	import { zod4Client } from 'sveltekit-superforms/adapters';
	import { clientEditSchema } from '$lib/schemas/clients.schema';
	import { Button } from '$lib/components/ui/button/index.js';
	import * as Dialog from '$lib/components/ui/dialog/index.js';
	import { Input } from '$lib/components/ui/input/index.js';
	import * as Tabs from '$lib/components/ui/tabs/index.js';
	import { Textarea } from '$lib/components/ui/textarea/index.js';
	import type { LayoutData } from './$types';
	let {
		data,
		children
	}: {
		data: LayoutData;
		children: import('svelte').Snippet;
	} = $props();

	let editOpen = $state(false);

	const tabs = [
		{ value: 'addresses', label: 'Addresses' },
		{ value: 'contacts', label: 'Contacts' },
		{ value: 'invoices', label: 'Invoices' },
		{ value: 'contracts', label: 'Contracts' },
		{ value: 'bookings', label: 'Bookings' }
	] as const;

	type TabValue = (typeof tabs)[number]['value'];

	let activeTab = $derived.by<TabValue>(() => {
		const segment = page.url.pathname.split('/').filter(Boolean).at(-1);
		return tabs.find((tab) => tab.value === segment)?.value ?? 'addresses';
	});

	// svelte-ignore state_referenced_locally
	const editForm = superForm(data.editForm, {
		validators: zod4Client(clientEditSchema),
		resetForm: false,
		onUpdated: ({ form }) => handleFormToast(form, 'clients-edit', () => (editOpen = false)),
		onError: ({ result }) => toast.error(result.error.message, { id: 'clients-edit' })
	});

	const { form: editData, enhance: enhanceEdit } = editForm;

	function handleFormToast(
		form: { valid: boolean; message?: string; errors: Record<string, unknown> },
		id: string,
		onSuccess: () => void
	) {
		if (form.valid) {
			if (form.message) toast.success(form.message, { id });
			onSuccess();
			return;
		}

		toast.error(form.message ?? firstError(form.errors), { id });
	}

	function firstError(errors: Record<string, unknown>) {
		for (const value of Object.values(errors)) {
			if (Array.isArray(value) && typeof value[0] === 'string') return value[0];
		}

		return 'Check the highlighted fields.';
	}

	function navigateToTab(tab: TabValue) {
		goto(resolve(`/dashboard/clients/[id]/${tab}`, { id: data.client.id }));
	}
</script>

<svelte:head>
	<title>{data.client.name} | Clearity</title>
</svelte:head>

<div class="flex flex-col gap-6">
	<div class="flex flex-col gap-4">
		<div class="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
			<div>
				<h1 class="text-2xl font-semibold tracking-tight">{data.client.name}</h1>
				<p class="text-sm text-muted-foreground">
					Client record for contacts, addresses, invoices, contracts, and bookings.
				</p>
			</div>
			<Dialog.Root bind:open={editOpen}>
				<Dialog.Trigger>
					{#snippet child({ props })}
						<Button {...props}>Edit client</Button>
					{/snippet}
				</Dialog.Trigger>
				<Dialog.Content class="max-h-[90vh] overflow-y-auto sm:max-w-2xl">
					<Dialog.Header>
						<Dialog.Title>Edit client</Dialog.Title>
						<Dialog.Description>Update this client record.</Dialog.Description>
					</Dialog.Header>
					<form method="POST" action="/dashboard/clients?/edit" class="grid gap-2" use:enhanceEdit>
						<input type="hidden" name="id" value={$editData.id} />
						<FormField form={editForm} name="name">
							<Field.Field>
								<Control id="edit-client-name">
									{#snippet children({ props })}
										<Field.Label>Name</Field.Label>
										<Input {...props} type="text" bind:value={$editData.name} />
									{/snippet}
								</Control>
								<Field.Error><FieldErrors /></Field.Error>
							</Field.Field>
						</FormField>
						<FormField form={editForm} name="industry">
							<Field.Field>
								<Control id="edit-client-industry">
									{#snippet children({ props })}
										<Field.Label>Industry</Field.Label>
										<FormSelect
											name="industry"
											bind:value={$editData.industry}
											options={industryOptions}
											triggerProps={props}
										/>
									{/snippet}
								</Control>
								<Field.Error><FieldErrors /></Field.Error>
							</Field.Field>
						</FormField>
						<FormField form={editForm} name="website">
							<Field.Field>
								<Control id="edit-client-website">
									{#snippet children({ props })}
										<Field.Label>Website</Field.Label>
										<Input
											{...props}
											type="url"
											placeholder="https://example.com"
											bind:value={$editData.website}
										/>
									{/snippet}
								</Control>
								<Field.Error><FieldErrors /></Field.Error>
							</Field.Field>
						</FormField>
						<FormField form={editForm} name="notes">
							<Field.Field>
								<Control id="edit-client-notes">
									{#snippet children({ props })}
										<Field.Label>Notes</Field.Label>
										<Textarea {...props} bind:value={$editData.notes} />
									{/snippet}
								</Control>
								<Field.Error><FieldErrors /></Field.Error>
							</Field.Field>
						</FormField>
						<Dialog.Footer>
							<Dialog.Close
								>{#snippet child({ props })}<Button variant="outline" {...props}>Cancel</Button
									>{/snippet}</Dialog.Close
							>
							<Button type="submit">Save changes</Button>
						</Dialog.Footer>
					</form>
				</Dialog.Content>
			</Dialog.Root>
		</div>
	</div>

	<div class="grid gap-3 rounded-lg border p-4 sm:grid-cols-2">
		<div>
			<p class="text-xs font-medium text-muted-foreground uppercase">Industry</p>
			<p class="text-sm">{industryLabel(data.client.industry)}</p>
		</div>
		<div>
			<p class="text-xs font-medium text-muted-foreground uppercase">Website</p>
			<p class="text-sm">{data.client.website ?? 'Not set'}</p>
		</div>
		<div class="sm:col-span-2">
			<p class="text-xs font-medium text-muted-foreground uppercase">Notes</p>
			<p class="text-sm whitespace-pre-wrap">{data.client.notes || 'Not set'}</p>
		</div>
	</div>

	<Tabs.Root value={activeTab} class="w-full">
		<Tabs.List class="flex h-auto flex-wrap justify-start">
			{#each tabs as tab (tab.value)}
				<Tabs.Trigger
					value={tab.value}
					onclick={() => navigateToTab(tab.value)}
					aria-label={`View ${tab.label.toLowerCase()}`}
				>
					{tab.label}
				</Tabs.Trigger>
			{/each}
		</Tabs.List>
		<div class="mt-4">
			{@render children()}
		</div>
	</Tabs.Root>
</div>
