<script lang="ts">
	import { goto } from '$app/navigation';
	import { client } from '$lib/graphql/client';
	import type { PageData } from './$types';
	import { ContentContainer } from '$lib/components/layout';
	import type { TeamProfile } from '$lib/graphql/queries/team';
	import type { CustomerProfile } from '$lib/graphql/queries/customerProfile';
	import {
		CREATE_CONVERSATION,
		type CreateConversationInput,
		type CreateConversationResult,
		type ParticipantInput
	} from '$lib/graphql/mutations/messaging';

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

	let teamProfiles = $derived(data.teamProfiles as TeamProfile[]);
	let customerProfiles = $derived((data.customerProfiles ?? []) as CustomerProfile[]);
	let isAdmin = $derived(data.isAdmin ?? false);
	let prefill = $derived(data.prefill);

	// Form state - initialize from prefill
	let subject = $state(data.prefill?.subject ?? '');
	let conversationType = $state<'DIRECT' | 'GROUP' | 'SUPPORT'>('GROUP');
	let entityType = $state<string | undefined>(data.prefill?.entityType);
	let entityId = $state<string | undefined>(data.prefill?.entityId);
	let initialMessage = $state('');
	let isCreating = $state(false);
	let error = $state('');

	// Selected participants with type info
	interface SelectedParticipant {
		id: string;
		type: 'team_profile' | 'customer_profile';
	}

	// Initialize from prefill (assume team_profile for backwards compatibility)
	let selectedParticipants = $state<SelectedParticipant[]>(
		(data.prefill?.participants ?? []).map((id: string) => ({
			id,
			type: 'team_profile' as const
		}))
	);

	// Tab state for admin
	let activeTab = $state<'team' | 'customers'>('team');

	// Search state
	let searchQuery = $state('');

	let filteredTeamProfiles = $derived(
		teamProfiles.filter(
			(p) =>
				p.fullName.toLowerCase().includes(searchQuery.toLowerCase()) ||
				(p.email?.toLowerCase().includes(searchQuery.toLowerCase()) ?? false)
		)
	);

	let filteredCustomerProfiles = $derived(
		customerProfiles.filter(
			(p) =>
				p.fullName.toLowerCase().includes(searchQuery.toLowerCase()) ||
				(p.email?.toLowerCase().includes(searchQuery.toLowerCase()) ?? false)
		)
	);

	// Check if any customer is selected (forces SUPPORT type)
	let hasCustomerParticipant = $derived(
		selectedParticipants.some((p) => p.type === 'customer_profile')
	);

	function isSelected(id: string, type: 'team_profile' | 'customer_profile'): boolean {
		return selectedParticipants.some((p) => p.id === id && p.type === type);
	}

	function toggleParticipant(id: string, type: 'team_profile' | 'customer_profile') {
		const existing = selectedParticipants.find((p) => p.id === id && p.type === type);
		if (existing) {
			selectedParticipants = selectedParticipants.filter((p) => !(p.id === id && p.type === type));
		} else {
			selectedParticipants = [...selectedParticipants, { id, type }];
		}
	}

	function getParticipantName(participant: SelectedParticipant): string {
		if (participant.type === 'team_profile') {
			return teamProfiles.find((p) => p.id === participant.id)?.fullName ?? 'Unknown';
		} else {
			return customerProfiles.find((p) => p.id === participant.id)?.fullName ?? 'Unknown';
		}
	}

	async function handleCreate() {
		if (selectedParticipants.length === 0) {
			error = 'Please select at least one participant';
			return;
		}

		isCreating = true;
		error = '';

		try {
			const participantIds: ParticipantInput[] = selectedParticipants.map((p) => ({
				participantType: p.type,
				participantId: p.id
			}));

			// Determine conversation type
			let finalType: 'DIRECT' | 'GROUP' | 'SUPPORT';
			if (hasCustomerParticipant) {
				// Customer conversations are always SUPPORT
				finalType = 'SUPPORT';
			} else if (selectedParticipants.length === 1) {
				finalType = 'DIRECT';
			} else {
				finalType = conversationType === 'SUPPORT' ? 'SUPPORT' : 'GROUP';
			}

			const input: CreateConversationInput = {
				subject: subject.trim() || undefined,
				conversationType: finalType,
				entityType: entityType || undefined,
				entityId: entityId || undefined,
				participantIds,
				initialMessage: initialMessage.trim() || undefined
			};

			const result = await client.mutate<CreateConversationResult>({
				mutation: CREATE_CONVERSATION,
				variables: { input }
			});

			if (result.data?.createConversation?.id) {
				goto(`/messages/${result.data.createConversation.id}`);
			}
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to create conversation';
		} finally {
			isCreating = false;
		}
	}
</script>

<svelte:head>
	<title>New Message - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		<!-- Header -->
		<div class="mb-6 flex items-center gap-4">
			<a
				href="/messages"
				class="hover:bg-theme-hover rounded p-1 text-theme-muted hover:text-theme"
				aria-label="Back to messages"
			>
				<svg class="h-5 w-5" 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>
			</a>
			<h1 class="text-2xl font-bold text-accent6-600 dark:text-accent6-400">New Message</h1>
		</div>

		{#if error}
			<div class="mb-6 rounded-lg bg-red-100 p-4 text-red-700 dark:bg-red-900/30 dark:text-red-400">
				{error}
			</div>
		{/if}

		<div class="rounded-lg border border-theme bg-theme-card p-6">
			<form
				onsubmit={(e) => {
					e.preventDefault();
					handleCreate();
				}}
			>
				<!-- Subject (optional) -->
				<label class="mb-4 block">
					<span class="mb-1 block text-sm font-medium text-theme">Subject (optional)</span>
					<input
						type="text"
						bind:value={subject}
						placeholder="Enter a subject for this conversation..."
						class="w-full rounded-lg border border-theme bg-theme px-4 py-2 text-theme placeholder:text-theme-muted"
					/>
				</label>

				<!-- Conversation type (shown only when multiple team participants, no customers) -->
				{#if selectedParticipants.length > 1 && !hasCustomerParticipant}
					<div class="mb-4">
						<span class="mb-2 block text-sm font-medium text-theme">Conversation Type</span>
						<div class="flex gap-4">
							<label class="flex items-center gap-2">
								<input
									type="radio"
									bind:group={conversationType}
									value="GROUP"
									class="text-accent-500"
								/>
								<span class="text-theme">Group</span>
							</label>
							<label class="flex items-center gap-2">
								<input
									type="radio"
									bind:group={conversationType}
									value="SUPPORT"
									class="text-accent-500"
								/>
								<span class="text-theme">Support</span>
							</label>
						</div>
					</div>
				{/if}

				{#if hasCustomerParticipant}
					<div
						class="mb-4 rounded-lg bg-blue-50 p-3 text-sm text-blue-700 dark:bg-blue-900/20 dark:text-blue-300"
					>
						<span class="font-medium">Support conversation</span> - Conversations with customers are automatically
						set as Support type and include dispatch.
					</div>
				{/if}

				<!-- Recipients -->
				<div class="mb-4">
					<span class="mb-2 block text-sm font-medium text-theme">Recipients</span>

					{#if selectedParticipants.length > 0}
						<div class="mb-3 flex flex-wrap gap-2">
							{#each selectedParticipants as participant}
								<span
									class="inline-flex items-center gap-1 rounded-full px-3 py-1 text-sm {participant.type ===
									'customer_profile'
										? 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400'
										: 'bg-accent-100 text-accent-800 dark:bg-accent-900/30 dark:text-accent-400'}"
								>
									{#if participant.type === 'customer_profile'}
										<svg class="h-3 w-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
											<path
												stroke-linecap="round"
												stroke-linejoin="round"
												stroke-width="2"
												d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
											/>
										</svg>
									{/if}
									{getParticipantName(participant)}
									<button
										type="button"
										class="ml-1 rounded-full p-0.5 hover:bg-accent-200 dark:hover:bg-accent-800"
										onclick={() => toggleParticipant(participant.id, participant.type)}
										aria-label="Remove {getParticipantName(participant)}"
									>
										<svg class="h-3 w-3" 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>
								</span>
							{/each}
						</div>
					{/if}

					<!-- Tabs for admin -->
					{#if isAdmin && customerProfiles.length > 0}
						<div class="mb-3 flex gap-1 rounded-lg bg-gray-100 p-1 dark:bg-gray-800">
							<button
								type="button"
								class="flex-1 rounded-md px-3 py-1.5 text-sm font-medium transition-colors {activeTab ===
								'team'
									? 'bg-white text-theme shadow dark:bg-gray-700'
									: 'text-theme-muted hover:text-theme'}"
								onclick={() => (activeTab = 'team')}
							>
								Team Members
							</button>
							<button
								type="button"
								class="flex-1 rounded-md px-3 py-1.5 text-sm font-medium transition-colors {activeTab ===
								'customers'
									? 'bg-white text-theme shadow dark:bg-gray-700'
									: 'text-theme-muted hover:text-theme'}"
								onclick={() => (activeTab = 'customers')}
							>
								Customers
							</button>
						</div>
					{/if}

					<!-- Search -->
					<label class="sr-only" for="search-profiles">
						{activeTab === 'team' ? 'Search team members' : 'Search customers'}
					</label>
					<input
						id="search-profiles"
						type="text"
						bind:value={searchQuery}
						placeholder={activeTab === 'team' ? 'Search team members...' : 'Search customers...'}
						class="mb-3 w-full rounded-lg border border-theme bg-theme px-4 py-2 text-theme placeholder:text-theme-muted"
					/>

					<!-- Profile list -->
					<div class="max-h-60 overflow-y-auto rounded-lg border border-theme">
						{#if activeTab === 'team'}
							{#each filteredTeamProfiles as profile (profile.id)}
								<button
									type="button"
									class="hover:bg-theme-hover flex w-full items-center gap-3 px-4 py-3 text-left transition-colors {isSelected(
										profile.id,
										'team_profile'
									)
										? 'bg-accent-50 dark:bg-accent-900/20'
										: ''}"
									onclick={() => toggleParticipant(profile.id, 'team_profile')}
								>
									<div
										class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-accent-100 font-semibold text-accent-600 dark:bg-accent-900/30 dark:text-accent-400"
									>
										{profile.fullName.charAt(0).toUpperCase()}
									</div>
									<div class="min-w-0 flex-1">
										<div class="font-medium text-theme">{profile.fullName}</div>
										{#if profile.email}
											<div class="truncate text-sm text-theme-muted">{profile.email}</div>
										{/if}
									</div>
									{#if isSelected(profile.id, 'team_profile')}
										<svg
											class="h-5 w-5 shrink-0 text-accent-500"
											fill="currentColor"
											viewBox="0 0 20 20"
										>
											<path
												fill-rule="evenodd"
												d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
												clip-rule="evenodd"
											/>
										</svg>
									{/if}
								</button>
							{:else}
								<div class="p-4 text-center text-theme-muted">No team members found</div>
							{/each}
						{:else}
							{#each filteredCustomerProfiles as profile (profile.id)}
								<button
									type="button"
									class="hover:bg-theme-hover flex w-full items-center gap-3 px-4 py-3 text-left transition-colors {isSelected(
										profile.id,
										'customer_profile'
									)
										? 'bg-purple-50 dark:bg-purple-900/20'
										: ''}"
									onclick={() => toggleParticipant(profile.id, 'customer_profile')}
								>
									<div
										class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-purple-100 font-semibold text-purple-600 dark:bg-purple-900/30 dark:text-purple-400"
									>
										{profile.fullName.charAt(0).toUpperCase()}
									</div>
									<div class="min-w-0 flex-1">
										<div class="font-medium text-theme">{profile.fullName}</div>
										{#if profile.email}
											<div class="truncate text-sm text-theme-muted">{profile.email}</div>
										{/if}
									</div>
									{#if isSelected(profile.id, 'customer_profile')}
										<svg
											class="h-5 w-5 shrink-0 text-purple-500"
											fill="currentColor"
											viewBox="0 0 20 20"
										>
											<path
												fill-rule="evenodd"
												d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
												clip-rule="evenodd"
											/>
										</svg>
									{/if}
								</button>
							{:else}
								<div class="p-4 text-center text-theme-muted">No customers found</div>
							{/each}
						{/if}
					</div>
				</div>

				<!-- Initial message -->
				<label class="mb-6 block">
					<span class="mb-1 block text-sm font-medium text-theme">Message</span>
					<textarea
						bind:value={initialMessage}
						placeholder="Write your message..."
						rows="4"
						class="w-full rounded-lg border border-theme bg-theme px-4 py-2 text-theme placeholder:text-theme-muted"
					></textarea>
				</label>

				<!-- Actions -->
				<div class="flex justify-end gap-3">
					<a href="/messages" class="btn-ghost">Cancel</a>
					<button
						type="submit"
						class="btn-primary"
						disabled={selectedParticipants.length === 0 || isCreating}
					>
						{isCreating ? 'Creating...' : 'Start Conversation'}
					</button>
				</div>
			</form>
		</div>
	</ContentContainer>
</div>
