<script lang="ts">
	import AdminListLayout from '$lib/components/admin/AdminListLayout.svelte';
	import ServiceForm from '$lib/components/admin/services/ServiceForm.svelte';
	import GenerateServicesModal from '$lib/components/admin/services/GenerateServicesModal.svelte';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import { goto } from '$app/navigation';
	import { invalidateDashboard } from '$lib/utils/invalidate';
	import { page } from '$app/state';
	import type { PageData } from './$types';
	import type { AdminServices$result } from '$houdini';
	import { formatAddress } from '$lib/utils/lookup';
	import { fromGlobalId } from '$lib/utils/relay';

	type Service = AdminServices$result['services'][number];

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

	// Auto-open create form if action=create is in URL
	$effect(() => {
		if (page.url.searchParams.get('action') === 'create') {
			showCreateForm();
			// Remove the action param from URL without navigation
			const newUrl = new URL(page.url);
			newUrl.searchParams.delete('action');
			goto(newUrl.pathname + newUrl.search, { replaceState: true, noScroll: true });
		}
	});

	// Use pre-built lookups from root layout
	let accountLookup = $derived(data.accountLookup);
	let nonAdminTeamIds = $derived(data.nonAdminTeamIds);
	let customers = $derived(data.customers?.data?.customers ?? []);
	let accounts = $derived(data.accounts?.data?.accounts ?? []);
	let teamProfiles = $derived(data.team?.data?.teamProfiles ?? []);

	// Get current status from URL, default to 'scheduled'
	let currentStatus = $derived(page.url.searchParams.get('status') || 'scheduled');

	// Extract data from each status and sort appropriately
	// Scheduled/In Progress: ascending by date (earliest first)
	// Completed: descending by date (most recent first)
	let scheduled = $derived(
		[...(data.services.scheduled ?? [])].sort((a, b) => a.date.localeCompare(b.date))
	);
	let inProgress = $derived(
		[...(data.services.inProgress ?? [])].sort((a, b) => a.date.localeCompare(b.date))
	);
	let completed = $derived(
		[...(data.services.completed ?? [])].sort((a, b) => b.date.localeCompare(a.date))
	);

	// Calculate counts for tabs
	let counts = $derived({
		scheduled: scheduled.length,
		inProgress: inProgress.length,
		completed: completed.length
	});

	// Select current data based on status
	let currentData = $derived(
		currentStatus === 'scheduled'
			? scheduled
			: currentStatus === 'in_progress'
				? inProgress
				: completed
	);

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

	// Generate modal state
	let showGenerateModal = $state(false);
	let filteredServices = $derived(() => {
		if (!searchQuery.trim()) return currentData;
		const query = searchQuery.toLowerCase();
		return currentData.filter((service) => {
			// Search account name
			if (service.accountAddressId) {
				const accountInfo = accountLookup.get(service.accountAddressId);
				if (accountInfo?.accountName.toLowerCase().includes(query)) return true;
				if (accountInfo?.addressName?.toLowerCase().includes(query)) return true;
			}
			return false;
		});
	});

	// Count non-admin team members
	function countNonAdminTeamMembers(teamMembers: { pk: string }[] | null | undefined): number {
		if (!teamMembers) return 0;
		return teamMembers.filter((m) => nonAdminTeamIds.has(m.pk)).length;
	}

	// Get admin profile UUID for dispatched check
	let adminProfileUuid = $derived(() => {
		const adminProfile = teamProfiles.find((p) => p.role === 'ADMIN');
		return adminProfile ? fromGlobalId(adminProfile.id) : null;
	});

	// Check if service is dispatched (admin is in team members)
	function isDispatched(teamMembers: { pk: string }[] | null | undefined): boolean {
		const adminUuid = adminProfileUuid();
		if (!adminUuid || !teamMembers) return false;
		return teamMembers.some((m) => m.pk === adminUuid);
	}

	// Check if service has non-admin team members assigned
	function hasNonAdminTeamMembers(teamMembers: { pk: string }[] | null | undefined): boolean {
		return countNonAdminTeamMembers(teamMembers) > 0;
	}

	// Format date for display
	function formatDate(dateStr: string): string {
		const date = new Date(dateStr + 'T00:00:00');
		return date.toLocaleDateString('en-US', {
			weekday: 'short',
			month: 'short',
			day: 'numeric'
		});
	}

	// Get status badge class
	function getStatusClass(status: string): string {
		switch (status) {
			case 'SCHEDULED':
				return 'badge-primary';
			case 'IN_PROGRESS':
				return 'badge-accent';
			case 'COMPLETED':
				return 'badge-secondary';
			default:
				return 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200';
		}
	}

	// Get service display info
	function getServiceDisplayInfo(service: Service): {
		accountName: string | null;
		addressName: string | null;
		address: string | null;
	} {
		if (service.accountAddressId) {
			const accountInfo = accountLookup.get(service.accountAddressId);
			return {
				accountName: accountInfo?.accountName ?? null,
				addressName: accountInfo?.addressName ?? null,
				address: accountInfo ? formatAddress(accountInfo) : null
			};
		}

		return {
			accountName: null,
			addressName: null,
			address: null
		};
	}

	function showCreateForm() {
		offCanvas.showRight({
			title: 'Create Service',
			content: createFormContent
		});
	}

	async function handleSuccess() {
		await invalidateDashboard();
	}

	// Determine empty text based on search
	let emptyText = $derived(
		searchQuery
			? `No services match "${searchQuery}". Try a different search term.`
			: 'No services found for this month and status.'
	);
</script>

{#snippet createFormContent()}
	<ServiceForm {customers} {accounts} {teamProfiles} onSuccess={handleSuccess} />
{/snippet}

{#snippet headerActions()}
	<button
		onclick={() => (showGenerateModal = true)}
		class="inline-flex shrink-0 items-center gap-2 rounded-lg border border-theme interactive bg-theme px-4 py-2 whitespace-nowrap text-theme"
	>
		<svg class="h-5 w-5" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
			<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>
		<span>Generate</span>
	</button>
	<a
		href="/admin/services/assign"
		class="inline-flex shrink-0 items-center gap-2 rounded-lg border border-theme interactive bg-theme px-4 py-2 whitespace-nowrap text-theme"
	>
		<svg class="h-5 w-5" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
			<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 2m-6 9l2 2 4-4"
			/>
		</svg>
		<span>Bulk Assign</span>
	</a>
{/snippet}

{#snippet emptyIcon()}
	<svg
		class="empty-state-icon text-secondary-400"
		style="fill: none"
		stroke="currentColor"
		viewBox="0 0 24 24"
	>
		<path
			stroke-linecap="round"
			stroke-linejoin="round"
			stroke-width="1.5"
			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>
{/snippet}

{#snippet serviceItem(service: Service)}
	{@const displayInfo = getServiceDisplayInfo(service)}
	{@const teamCount = countNonAdminTeamMembers(service.teamMembers)}
	<a href="/admin/services/{service.id}" class="block">
		<div class="card-service">
			<div class="flex items-start justify-between gap-4">
				<div class="min-w-0 flex-1 space-y-1">
					<!-- Row 1: Date + Status badges -->
					<div class="flex flex-wrap items-center gap-2">
						<span
							class="rounded-full border border-theme bg-theme-secondary px-3 py-1 text-xs font-medium text-theme"
						>
							{formatDate(service.date)}
						</span>
						<span
							class="rounded-full px-3 py-1 text-xs font-medium {getStatusClass(service.status)}"
						>
							{service.status.replace('_', ' ')}
						</span>
						{#if isDispatched(service.teamMembers)}
							<span
								class="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}
						{#if hasNonAdminTeamMembers(service.teamMembers)}
							<span
								class="rounded-full bg-blue-100 px-3 py-1 text-xs font-medium text-blue-700 dark:bg-blue-900/30 dark:text-blue-400"
							>
								Assigned
							</span>
						{/if}
					</div>
					<!-- Row 2: Account Name -->
					{#if displayInfo.accountName}
						<p class="text-base font-semibold text-primary-500">
							{displayInfo.accountName}
						</p>
					{:else}
						<p class="text-base font-semibold text-theme-muted italic">No account linked</p>
					{/if}
					<!-- Row 3: Address Name (location name) -->
					{#if displayInfo.addressName}
						<p class="text-sm text-theme-secondary">{displayInfo.addressName}</p>
					{/if}
					<!-- Row 4: Address -->
					{#if displayInfo.address}
						<p class="text-sm text-theme-muted">{displayInfo.address}</p>
					{/if}
					<!-- Row 5: Team count -->
					<div class="flex flex-wrap items-center gap-4 text-sm text-theme-muted">
						<span>{teamCount} team member{teamCount !== 1 ? 's' : ''}</span>
					</div>
					<!-- Row 6: Notes -->
					{#if service.notes}
						<p class="line-clamp-2 text-sm text-theme-muted italic">{service.notes}</p>
					{/if}
				</div>
				<svg
					class="mt-1 h-5 w-5 flex-shrink-0 text-theme-muted"
					style="fill: none"
					viewBox="0 0 24 24"
					stroke="currentColor"
					stroke-width="2"
				>
					<path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" />
				</svg>
			</div>
		</div>
	</a>
{/snippet}

<AdminListLayout
	title="Services"
	subtitle="Manage recurring service appointments. View scheduled services, track progress, and review completed work."
	items={filteredServices()}
	{currentStatus}
	currentMonth={data.currentMonth}
	{counts}
	emptyTitle="No Services"
	{emptyText}
	colorScheme="secondary"
	{searchQuery}
	onSearchChange={(q) => (searchQuery = q)}
	searchPlaceholder="Search services..."
	createButtonText="New Service"
	onCreateClick={showCreateForm}
	{emptyIcon}
	item={serviceItem}
	{headerActions}
/>

<GenerateServicesModal
	bind:open={showGenerateModal}
	{accounts}
	initialMonth={parseInt(data.currentMonth.split('-')[1])}
	initialYear={parseInt(data.currentMonth.split('-')[0])}
	onClose={() => (showGenerateModal = false)}
	onSuccess={async () => {
		await invalidateDashboard();
	}}
/>
