<script lang="ts">
	import type { PageData } from './$types';
	import type { LayoutData } from '../../$types';
	import { goto } from '$app/navigation';
	import { createConversation, sendMessage } from '$lib/utils/messages';
	import { formatDate } from '$lib/utils/date';
	import type { CustomerAccountInfo } from '../../customer/+layout.server';

	// Service/Project types from customer data
	interface CustomerService {
		id: string;
		date: string;
		status: string;
		accountAddressId?: string | null;
	}

	interface CustomerProject {
		id: string;
		name: string;
		date: string;
		status: string;
	}

	interface CustomerAccount {
		id: string;
		name: string;
	}

	interface Props {
		data: PageData & {
			user?: LayoutData['user'];
			team?: LayoutData['team'];
			teamMemberLookup?: LayoutData['teamMemberLookup'];
			// Customer-specific data from customer layout
			accounts?: { data?: { accounts?: CustomerAccount[] } };
			services?: {
				upcoming?: { data?: { services?: CustomerService[] } };
				completed?: { data?: { services?: CustomerService[] } };
			};
			projects?: {
				upcoming?: { data?: { projects?: CustomerProject[] } };
				completed?: { data?: { projects?: CustomerProject[] } };
			};
			customerAccountLookup?: Record<string, CustomerAccountInfo>;
		};
	}

	let { data }: Props = $props();

	// Get user type from layout data
	let user = $derived(data.user?.data?.me);
	let isCustomer = $derived(user?.__typename === 'CustomerProfileType');

	// Team member lookup for displaying names (uses UUIDs)
	let teamMemberLookup = $derived(data.teamMemberLookup ?? new Map());

	// Find the admin profile (Nexus Dispatch) for support message routing
	let adminProfile = $derived(
		data.team?.data?.teamProfiles?.find((p) => p.role === 'ADMIN') ?? null
	);

	// Customer data for entity selection
	let customerAccounts = $derived(data.accounts?.data?.accounts ?? []);
	let customerAccountLookup = $derived(data.customerAccountLookup ?? {});
	let customerServices = $derived([
		...(data.services?.upcoming?.data?.services ?? []),
		...(data.services?.completed?.data?.services ?? [])
	]);
	let customerProjects = $derived([
		...(data.projects?.upcoming?.data?.projects ?? []),
		...(data.projects?.completed?.data?.projects ?? [])
	]);

	// Check if this is a pre-filled message from a service/project page
	let isEntityLinked = $derived(!!data.entityType && !!data.entityId);
	let subjectPrefix = $derived(data.subject ?? '');

	// Form state
	let subjectSuffix = $state('');
	let subject = $state(data.subject ?? '');
	let conversationType = $state(
		data.conversationType ??
			(data.user?.data?.me?.__typename === 'CustomerProfileType' ? 'SUPPORT' : 'DIRECT')
	);
	let participantInput = $state('');
	let participantIds = $state<string[]>(data.participantIds ?? []);
	let entityType = $state(data.entityType ?? '');
	let entityId = $state(data.entityId ?? '');
	let customerEntitySelection = $state(''); // Combined "Type:Id" for customer dropdown
	let initialMessage = $state('');
	let isSubmitting = $state(false);
	let error = $state('');

	// Build entity options for customer dropdown
	interface EntityOption {
		value: string; // "Type:Id"
		label: string;
		group: string;
	}

	let customerEntityOptions = $derived.by((): EntityOption[] => {
		const options: EntityOption[] = [];

		// Add accounts
		for (const account of customerAccounts) {
			options.push({
				value: `Account:${account.id}`,
				label: account.name,
				group: 'Accounts'
			});
		}

		// Add services (upcoming first, then completed)
		for (const service of customerServices) {
			const accountInfo = service.accountAddressId
				? customerAccountLookup[service.accountAddressId]
				: null;
			const dateStr = formatDate(service.date) || 'Unknown date';
			const accountName = accountInfo?.name ?? 'Service';
			const status = service.status === 'COMPLETED' ? ' (Completed)' : '';
			options.push({
				value: `Service:${service.id}`,
				label: `${dateStr} - ${accountName}${status}`,
				group: 'Services'
			});
		}

		// Add projects
		for (const project of customerProjects) {
			const dateStr = formatDate(project.date) || '';
			const status = project.status === 'COMPLETED' ? ' (Completed)' : '';
			const parts = [dateStr, project.name].filter(Boolean);
			options.push({
				value: `Project:${project.id}`,
				label: `${parts.join(' - ')}${status}`,
				group: 'Projects'
			});
		}

		return options;
	});

	// Parse customer entity selection into type and id
	$effect(() => {
		if (customerEntitySelection) {
			const [type, id] = customerEntitySelection.split(':');
			entityType = type;
			entityId = id;
		} else {
			entityType = '';
			entityId = '';
		}
	});

	// Build full subject from prefix + suffix when entity is linked
	let fullSubject = $derived(
		isEntityLinked
			? subjectSuffix.trim()
				? `${subjectPrefix} - ${subjectSuffix.trim()}`
				: subjectPrefix
			: subject
	);

	// Lock participants if provided via URL params (pre-selected from service/project page)
	let participantsLocked = $derived(data.participantIds && data.participantIds.length > 0);

	// Conversation types available based on user role
	let availableTypes = $derived(
		isCustomer
			? [{ value: 'SUPPORT', label: 'Support Request' }]
			: [
					{ value: 'DIRECT', label: 'Direct Message' },
					{ value: 'GROUP', label: 'Group Conversation' },
					{ value: 'SUPPORT', label: 'Support' }
				]
	);

	// Look up participant name from team member lookup (UUID) or team profiles (Global ID)
	function getParticipantName(id: string): string {
		// First try the UUID-based lookup
		const member = teamMemberLookup.get(id);
		if (member) return member.fullName;

		// Then try to find by Global ID in team profiles
		const profile = data.team?.data?.teamProfiles?.find((p) => p.id === id);
		if (profile) return profile.fullName ?? id;

		return id;
	}

	async function handleSubmit() {
		error = '';

		// Validation
		if (!fullSubject.trim()) {
			error = 'Subject is required';
			return;
		}

		if (participantIds.length === 0 && conversationType !== 'SUPPORT') {
			error = 'At least one participant is required';
			return;
		}

		isSubmitting = true;

		try {
			// For SUPPORT conversations, automatically add admin (Nexus Dispatch) as participant
			let finalParticipantIds = [...participantIds];
			if (conversationType === 'SUPPORT' && adminProfile) {
				// adminProfile.id is already a Global ID from the GraphQL query
				// createConversation will handle any necessary conversions
				if (!finalParticipantIds.includes(adminProfile.id)) {
					finalParticipantIds.push(adminProfile.id);
				}
			}

			// Create conversation
			const conversation = await createConversation({
				subject: fullSubject.trim(),
				conversationType,
				participantIds: finalParticipantIds,
				entityType: entityType || undefined,
				entityId: entityId || undefined
			});

			if (!conversation) {
				error = 'Failed to create conversation';
				return;
			}

			// Send initial message if provided
			if (initialMessage.trim()) {
				await sendMessage({
					conversationId: conversation.id,
					body: initialMessage.trim()
				});
			}

			// Navigate to the new conversation
			goto(`/messages/${conversation.id}`);
		} catch (err) {
			console.error('Failed to create conversation:', err);
			error = err instanceof Error ? err.message : 'Failed to create conversation';
		} finally {
			isSubmitting = false;
		}
	}

	function addParticipant() {
		const id = participantInput.trim();
		if (id && !participantIds.includes(id)) {
			participantIds = [...participantIds, id];
			participantInput = '';
		}
	}

	function removeParticipant(id: string) {
		participantIds = participantIds.filter((p) => p !== id);
	}

	function handleParticipantKeyDown(event: KeyboardEvent) {
		if (event.key === 'Enter') {
			event.preventDefault();
			addParticipant();
		}
	}

	function goBack() {
		goto('/messages');
	}
</script>

<svelte:head>
	<title>New Conversation | Nexus</title>
</svelte:head>

<div class="mx-auto max-w-2xl px-4 py-6">
	<!-- Header -->
	<div class="mb-6 flex items-center gap-3">
		<button onclick={goBack} class="rounded-lg interactive p-2" aria-label="Go back">
			<svg
				class="h-5 w-5 text-theme-secondary"
				style="fill: none"
				stroke="currentColor"
				viewBox="0 0 24 24"
			>
				<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
			</svg>
		</button>
		<h1 class="text-xl font-semibold text-theme">New Conversation</h1>
	</div>

	<!-- Form -->
	<form
		onsubmit={(e) => {
			e.preventDefault();
			handleSubmit();
		}}
		class="space-y-6"
	>
		<!-- Error message -->
		{#if error}
			<div
				class="rounded-lg bg-error-50 p-4 text-sm text-error-700 dark:bg-error-900/20 dark:text-error-300"
			>
				{error}
			</div>
		{/if}

		<!-- Conversation Type -->
		{#if !isCustomer}
			<div>
				<label for="type" class="mb-2 block text-sm font-medium text-theme">Conversation Type</label
				>
				<select
					id="type"
					bind:value={conversationType}
					class="w-full rounded-lg border border-theme bg-theme px-4 py-2.5 text-sm text-theme transition-all outline-none focus:border-primary-500"
				>
					{#each availableTypes as type (type.value)}
						<option value={type.value}>{type.label}</option>
					{/each}
				</select>
			</div>
		{:else}
			<div class="rounded-lg bg-primary-50 p-4 dark:bg-primary-900/20">
				<div class="flex items-center gap-2 text-sm text-primary-700 dark:text-primary-300">
					<svg class="h-5 w-5" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M18.364 5.636l-3.536 3.536m0 5.656l3.536 3.536M9.172 9.172L5.636 5.636m3.536 9.192l-3.536 3.536M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-5 0a4 4 0 11-8 0 4 4 0 018 0z"
						/>
					</svg>
					<span
						>Your message will be sent to <strong>{adminProfile?.fullName ?? 'Support'}</strong
						></span
					>
				</div>
			</div>

			<!-- Customer entity selection -->
			{#if customerEntityOptions.length > 0}
				<div>
					<label for="customerEntity" class="mb-2 block text-sm font-medium text-theme">
						Regarding
						<span class="font-normal text-theme-muted">(optional)</span>
					</label>
					<select
						id="customerEntity"
						bind:value={customerEntitySelection}
						class="w-full rounded-lg border border-theme bg-theme px-4 py-2.5 text-sm text-theme transition-all outline-none focus:border-primary-500"
					>
						<option value="">General inquiry</option>
						{#if customerAccounts.length > 0}
							<optgroup label="Accounts">
								{#each customerEntityOptions.filter((o) => o.group === 'Accounts') as option (option.value)}
									<option value={option.value}>{option.label}</option>
								{/each}
							</optgroup>
						{/if}
						{#if customerServices.length > 0}
							<optgroup label="Services">
								{#each customerEntityOptions.filter((o) => o.group === 'Services') as option (option.value)}
									<option value={option.value}>{option.label}</option>
								{/each}
							</optgroup>
						{/if}
						{#if customerProjects.length > 0}
							<optgroup label="Projects">
								{#each customerEntityOptions.filter((o) => o.group === 'Projects') as option (option.value)}
									<option value={option.value}>{option.label}</option>
								{/each}
							</optgroup>
						{/if}
					</select>
				</div>
			{/if}
		{/if}

		<!-- Subject -->
		<div>
			<label for="subject" class="mb-2 block text-sm font-medium text-theme">Subject</label>
			{#if isEntityLinked}
				<!-- Locked prefix with editable suffix -->
				<div class="space-y-2">
					<div
						class="rounded-lg border border-theme bg-black/5 px-4 py-2.5 text-sm text-theme dark:bg-white/5"
					>
						{subjectPrefix}
					</div>
					<input
						id="subject"
						type="text"
						bind:value={subjectSuffix}
						placeholder="Add additional context (optional)..."
						class="w-full rounded-lg border border-theme bg-theme px-4 py-2.5 text-sm text-theme transition-all outline-none placeholder:text-theme-muted focus:border-primary-500"
					/>
				</div>
			{:else}
				<input
					id="subject"
					type="text"
					bind:value={subject}
					placeholder="What's this conversation about?"
					class="w-full rounded-lg border border-theme bg-theme px-4 py-2.5 text-sm text-theme transition-all outline-none placeholder:text-theme-muted focus:border-primary-500"
				/>
			{/if}
		</div>

		<!-- Participants (not for customers) -->
		{#if !isCustomer}
			<div>
				<label for="participants" class="mb-2 block text-sm font-medium text-theme">
					{#if participantsLocked}
						To
					{:else}
						Participants
						{#if conversationType === 'DIRECT'}
							<span class="font-normal text-theme-muted">(Enter recipient ID)</span>
						{:else if conversationType === 'GROUP'}
							<span class="font-normal text-theme-muted">(Add multiple participants)</span>
						{/if}
					{/if}
				</label>

				{#if !participantsLocked}
					<div class="flex gap-2">
						<input
							id="participants"
							type="text"
							bind:value={participantInput}
							onkeydown={handleParticipantKeyDown}
							placeholder="Enter participant ID..."
							class="flex-1 rounded-lg border border-theme bg-theme px-4 py-2.5 text-sm text-theme transition-all outline-none placeholder:text-theme-muted focus:border-primary-500"
						/>
						<button
							type="button"
							onclick={addParticipant}
							class="rounded-lg bg-black/5 px-4 py-2.5 text-sm font-medium text-theme-secondary transition-colors hover:bg-black/10 dark:bg-white/10 dark:hover:bg-white/15"
						>
							Add
						</button>
					</div>
				{/if}

				{#if participantIds.length > 0}
					<div class="mt-3 flex flex-wrap gap-2">
						{#each participantIds as id (id)}
							<span
								class="inline-flex items-center gap-1 rounded-full bg-primary-100 px-3 py-1 text-sm text-primary-700 dark:bg-primary-900/30 dark:text-primary-300"
							>
								{getParticipantName(id)}
								{#if !participantsLocked}
									<button
										type="button"
										onclick={() => removeParticipant(id)}
										class="ml-1 rounded-full p-0.5 transition-colors hover:bg-primary-200 dark:hover:bg-primary-800"
										aria-label="Remove participant"
									>
										<svg
											class="h-3 w-3"
											style="fill: none"
											stroke="currentColor"
											viewBox="0 0 24 24"
										>
											<path
												stroke-linecap="round"
												stroke-linejoin="round"
												stroke-width="2"
												d="M6 18L18 6M6 6l12 12"
											/>
										</svg>
									</button>
								{/if}
							</span>
						{/each}
					</div>
				{/if}
			</div>
		{/if}

		<!-- Entity link indicator (shown when message initiated from service/project) -->
		{#if isEntityLinked}
			<div class="rounded-lg border border-theme bg-black/5 p-3 dark:bg-white/5">
				<div class="flex items-center gap-2 text-sm">
					<svg
						class="h-4 w-4 text-theme-muted"
						style="fill: none"
						stroke="currentColor"
						viewBox="0 0 24 24"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"
						/>
					</svg>
					<span class="text-theme-muted">Linked to {data.entityType}</span>
				</div>
			</div>
		{/if}

		<!-- Initial Message -->
		<div>
			<label for="message" class="mb-2 block text-sm font-medium text-theme">
				Initial Message
				<span class="font-normal text-theme-muted">(optional)</span>
			</label>
			<textarea
				id="message"
				bind:value={initialMessage}
				placeholder="Write your first message..."
				rows="4"
				class="w-full resize-none rounded-lg border border-theme bg-theme px-4 py-2.5 text-sm text-theme transition-all outline-none placeholder:text-theme-muted focus:border-primary-500"
			></textarea>
		</div>

		<!-- Submit -->
		<div class="flex justify-end gap-3">
			<button
				type="button"
				onclick={goBack}
				class="rounded-lg interactive px-4 py-2.5 text-sm font-medium text-theme-secondary"
			>
				Cancel
			</button>
			<button
				type="submit"
				disabled={isSubmitting}
				class="inline-flex items-center gap-2 rounded-lg bg-primary-600 px-6 py-2.5 text-sm font-medium text-white transition-colors hover:bg-primary-700 disabled:opacity-50"
			>
				{#if isSubmitting}
					<svg
						class="h-4 w-4 animate-spin"
						style="fill: none"
						stroke="currentColor"
						viewBox="0 0 24 24"
					>
						<circle class="opacity-25" cx="12" cy="12" r="10" stroke-width="4"></circle>
						<path
							class="opacity-75"
							d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
						></path>
					</svg>
					Creating...
				{:else}
					Create Conversation
				{/if}
			</button>
		</div>
	</form>
</div>
