<script lang="ts">
	import { formatDate } from '$lib/utils/date';
	import { goto } from '$app/navigation';
	import { fromGlobalId } from '$lib/utils/relay';

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

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

	interface CustomerInfo {
		customerName: string;
	}

	interface WaveProduct {
		id: string;
		name: string;
		description: string | null;
		unitPrice: number | string;
		isArchived: boolean;
	}

	interface Props {
		projectId: string;
		projectName: string | null;
		status: string;
		date: string | null;
		amount: number | string | null;
		labor: number | string | null;
		address: string | null;
		teamMembers: TeamMember[];
		notes: string | null;
		calendarEventId?: string | null;
		waveServiceId?: string | null;
		waveProducts?: WaveProduct[];
		onScheduleEvent?: () => void;
		accountInfo?: AccountInfo | null;
		customerInfo?: CustomerInfo | null;
		isDispatched?: boolean;
	}

	let {
		projectId,
		projectName,
		status,
		date,
		amount,
		labor,
		address,
		teamMembers,
		notes,
		calendarEventId,
		waveServiceId,
		waveProducts = [],
		onScheduleEvent,
		accountInfo,
		customerInfo,
		isDispatched = false
	}: Props = $props();

	// Find linked Wave product
	let linkedProduct = $derived(
		waveServiceId ? waveProducts.find((p) => fromGlobalId(p.id) === waveServiceId) : null
	);

	// 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 = formatDate(date) || 'Unknown Date';
		const accountName = accountInfo?.accountName || customerInfo?.customerName || 'Unknown';
		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: 'Project',
			entityId: projectId,
			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: 'Project',
			entityId: projectId,
			participantIds: memberIds,
			conversationType: 'GROUP',
			subject: messageSubject()
		});
		goto(`/messages/new?${params.toString()}`);
	}

	function formatCurrency(value: number | string | null | undefined): string {
		if (value == null) return '$0';
		const num = typeof value === 'string' ? parseFloat(value) : value;
		return new Intl.NumberFormat('en-US', {
			style: 'currency',
			currency: 'USD',
			minimumFractionDigits: 0,
			maximumFractionDigits: 0
		}).format(num);
	}

	function getStatusBadgeClass(projectStatus: string): string {
		switch (projectStatus) {
			case 'SCHEDULED':
				return 'badge-primary';
			case 'IN_PROGRESS':
				return 'badge-accent';
			default:
				return 'badge-secondary';
		}
	}
</script>

<div class="mb-6 rounded-xl border border-theme bg-theme-card p-6">
	<div class="mb-4 flex items-center justify-between">
		<h2 class="text-lg font-semibold text-theme">Project Details</h2>
		{#if calendarEventId}
			<a
				href="/admin/calendar/{calendarEventId}"
				class="inline-flex items-center gap-2 rounded-lg bg-accent7-500/10 px-3 py-1.5 text-sm font-medium text-accent7-600 transition-colors hover:bg-accent7-500/20 dark:text-accent7-400"
			>
				<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 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
					/>
				</svg>
				View Event
			</a>
		{:else if onScheduleEvent}
			<button
				type="button"
				onclick={onScheduleEvent}
				class="inline-flex items-center gap-2 rounded-lg bg-accent7-500/10 px-3 py-1.5 text-sm font-medium text-accent7-600 transition-colors hover:bg-accent7-500/20 dark:text-accent7-400"
			>
				<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 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
					/>
				</svg>
				Schedule Event
			</button>
		{/if}
	</div>
	<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
		<!-- Status -->
		<div>
			<p class="detail-label">Status</p>
			<div class="flex flex-wrap gap-2">
				<span
					class="inline-block rounded-full px-3 py-1 text-xs font-medium {getStatusBadgeClass(
						status
					)}"
				>
					{status.replace('_', ' ')}
				</span>
				{#if isDispatched}
					<span
						class="inline-block rounded-full bg-emerald-100 px-3 py-1 text-xs font-medium text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400"
					>
						Dispatched
					</span>
				{/if}
			</div>
		</div>

		<!-- Date -->
		<div>
			<p class="detail-label">Date</p>
			<p class="text-theme">{formatDate(date)}</p>
		</div>

		<!-- Amount -->
		<div>
			<p class="detail-label">Amount</p>
			<p class="font-semibold text-theme">{formatCurrency(amount)}</p>
		</div>

		<!-- Labor -->
		<div>
			<p class="detail-label">Labor</p>
			<p class="text-theme">{formatCurrency(labor)}</p>
		</div>
	</div>

	<!-- Address -->
	{#if address}
		<div class="mt-4 border-t border-theme pt-4">
			<p class="detail-label">Address</p>
			<p class="text-theme">{address}</p>
		</div>
	{/if}

	<!-- Team Members -->
	{#if teamMembers.length > 0}
		<div class="mt-4 border-t border-theme pt-4">
			<div class="mb-2 flex items-center justify-between">
				<p class="detail-label">Team</p>
				{#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>
			<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'
								? 'bg-accent-500/20 text-accent-600 dark:text-accent-400'
								: 'bg-secondary-500/20 text-secondary-600 dark:text-secondary-400'}"
						>
							{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>
		</div>
	{/if}

	<!-- Wave Integration -->
	{#if waveServiceId}
		<div class="mt-4 border-t border-theme pt-4">
			<p class="detail-label">Wave Integration</p>
			<div class="flex items-center gap-2">
				<span class="badge-primary">Linked</span>
				{#if linkedProduct}
					<span class="text-theme">{linkedProduct.name}</span>
				{/if}
			</div>
			<p class="mt-1 font-mono text-xs text-theme-muted">{waveServiceId}</p>
		</div>
	{/if}

	<!-- Notes -->
	{#if notes}
		<div class="mt-4 border-t border-theme pt-4">
			<p class="detail-label">Notes</p>
			<p class="whitespace-pre-wrap text-theme-secondary">{notes}</p>
		</div>
	{/if}
</div>
