<script lang="ts">
	import { formatDate, formatStatus, getStatusBadgeClass } from '$lib/utils/format';
	import { formatDate as formatDateUtil } from '$lib/utils/date';
	import { goto } from '$app/navigation';

	interface TeamMember {
		id: string;
		fullName: string;
		role: string;
	}

	interface AccountInfo {
		accountName: string;
		addressName: string;
	}

	interface CustomerInfo {
		customerName: string;
	}

	interface Props {
		entityType: 'service' | 'project';
		entityId: string;
		status: string;
		date: string;
		address?: string | null;
		teamMembers: TeamMember[];
		notes?: string | null;
		// Project-specific
		projectName?: string | null;
		accountInfo?: AccountInfo | null;
		customerInfo?: CustomerInfo | null;
	}

	let {
		entityType,
		entityId,
		status,
		date,
		address,
		teamMembers,
		notes,
		projectName,
		accountInfo,
		customerInfo
	}: Props = $props();

	// Non-admin team members for messaging (exclude ADMIN role)
	let messagableMembers = $derived(teamMembers.filter((m) => m.role !== 'ADMIN'));

	// Build the subject line for messages
	let messageSubject = $derived(() => {
		const formattedDate = formatDateUtil(date) || 'Unknown Date';
		const accountName = accountInfo?.accountName || customerInfo?.customerName || 'Unknown';

		if (entityType === 'service') {
			return `${formattedDate} - Service: ${accountName}`;
		} else {
			const name = projectName || 'Project';
			return `${formattedDate} - Project: ${name} - ${accountName}`;
		}
	});

	// Navigate to new message page with pre-filled params
	function messageTeamMember(memberId: string) {
		const params = new URLSearchParams({
			entityType: entityType === 'service' ? 'Service' : 'Project',
			entityId,
			participantIds: memberId,
			conversationType: 'DIRECT',
			subject: messageSubject()
		});
		goto(`/messages/new?${params.toString()}`);
	}

	// Navigate to new message page with all team members
	function messageAllTeamMembers() {
		const memberIds = messagableMembers.map((m) => m.id).join(',');
		const params = new URLSearchParams({
			entityType: entityType === 'service' ? 'Service' : 'Project',
			entityId,
			participantIds: memberIds,
			conversationType: 'GROUP',
			subject: messageSubject()
		});
		goto(`/messages/new?${params.toString()}`);
	}

	let colorClasses = $derived(
		entityType === 'service'
			? {
					icon: 'bg-secondary-500/10',
					iconText: 'text-secondary-600 dark:text-secondary-400',
					leaderBadge: 'bg-accent-500/20 text-accent-600 dark:text-accent-400',
					memberBadge: 'bg-secondary-500/20 text-secondary-600 dark:text-secondary-400'
				}
			: {
					icon: 'bg-accent-500/10',
					iconText: 'text-accent-600 dark:text-accent-400',
					leaderBadge: 'bg-accent-500/20 text-accent-600 dark:text-accent-400',
					memberBadge: 'bg-secondary-500/20 text-secondary-600 dark:text-secondary-400'
				}
	);

	let title = $derived(entityType === 'service' ? 'Service Details' : 'Project Details');
</script>

<section class="mb-8">
	<div class="mb-4 flex items-center gap-2">
		<div class="flex h-8 w-8 items-center justify-center rounded-lg {colorClasses.icon}">
			{#if entityType === 'service'}
				<svg
					class="h-5 w-5 {colorClasses.iconText}"
					style="fill: none"
					stroke="currentColor"
					viewBox="0 0 24 24"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="2"
						d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"
					/>
				</svg>
			{:else}
				<svg
					class="h-5 w-5 {colorClasses.iconText}"
					style="fill: none"
					stroke="currentColor"
					viewBox="0 0 24 24"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="2"
						d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"
					/>
				</svg>
			{/if}
		</div>
		<h2 class="text-lg font-semibold text-theme">{title}</h2>
	</div>

	<div class="card-padded">
		<div class="space-y-4">
			<!-- Status & Date Row -->
			<div class="flex flex-wrap items-center gap-3">
				<span class="rounded-full px-3 py-1 text-sm font-medium {getStatusBadgeClass(status)}">
					{formatStatus(status)}
				</span>
				<span class="text-theme-secondary">
					{formatDate(date)}
				</span>
			</div>

			<!-- Account/Customer Info (projects only) -->
			{#if entityType === 'project' && accountInfo}
				<div class="border-t border-theme pt-2">
					<h3 class="mb-1 text-sm font-medium text-theme-muted">Account</h3>
					<p class="font-medium text-theme">{accountInfo.accountName}</p>
					<p class="text-sm text-theme-secondary">{accountInfo.addressName}</p>
				</div>
			{:else if entityType === 'project' && customerInfo}
				<div class="border-t border-theme pt-2">
					<h3 class="mb-1 text-sm font-medium text-theme-muted">Customer</h3>
					<p class="font-medium text-theme">{customerInfo.customerName}</p>
				</div>
			{/if}

			<!-- Address Section -->
			{#if address}
				<div class="border-t border-theme pt-2">
					<h3 class="mb-1 text-sm font-medium text-theme-muted">Address</h3>
					<p class="text-theme">{address}</p>
				</div>
			{/if}

			<!-- Team Members -->
			<div class="border-t border-theme pt-2">
				<div class="mb-2 flex items-center justify-between">
					<h3 class="text-sm font-medium text-theme-muted">Team Members</h3>
					{#if messagableMembers.length >= 2}
						<button
							type="button"
							onclick={messageAllTeamMembers}
							class="inline-flex items-center gap-1.5 rounded-lg bg-primary-600 px-3 py-1.5 text-xs font-medium text-white transition-colors hover:bg-primary-700"
						>
							<svg class="h-3.5 w-3.5" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
								<path
									stroke-linecap="round"
									stroke-linejoin="round"
									stroke-width="2"
									d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"
								/>
							</svg>
							Message Team
						</button>
					{/if}
				</div>
				{#if teamMembers.length === 0}
					<p class="text-theme-muted italic">No team members assigned</p>
				{:else}
					<div class="space-y-2">
						{#each teamMembers as member (member.id)}
							<div class="flex items-center gap-2">
								<span
									class="inline-flex h-6 w-6 items-center justify-center rounded text-xs font-bold {member.role ===
									'TEAM_LEADER'
										? colorClasses.leaderBadge
										: colorClasses.memberBadge}"
								>
									{member.role === 'TEAM_LEADER' ? 'TL' : 'TM'}
								</span>
								{#if member.role !== 'ADMIN'}
									<button
										type="button"
										onclick={() => messageTeamMember(member.id)}
										class="rounded-full p-1 text-theme-muted transition-colors hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
										aria-label="Message {member.fullName}"
									>
										<svg
											class="h-4 w-4"
											style="fill: none"
											stroke="currentColor"
											viewBox="0 0 24 24"
										>
											<path
												stroke-linecap="round"
												stroke-linejoin="round"
												stroke-width="2"
												d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
											/>
										</svg>
									</button>
								{:else}
									<!-- Spacer to maintain alignment for admin members -->
									<span class="h-6 w-6"></span>
								{/if}
								<span class="text-theme">{member.fullName}</span>
							</div>
						{/each}
					</div>
				{/if}
			</div>

			<!-- Notes -->
			{#if notes}
				<div class="border-t border-theme pt-2">
					<h3 class="mb-1 text-sm font-medium text-theme-muted">Notes</h3>
					<p class="whitespace-pre-wrap text-theme">{notes}</p>
				</div>
			{/if}
		</div>
	</div>
</section>
