<script lang="ts">
	import { goto } from '$app/navigation';
	import type { PageData } from './$types';
	import { ContentContainer } from '$lib/components/layout';
	import {
		MonthSelector,
		StatusTabs,
		Pagination,
		AdminDashboardHeader
	} from '$lib/components/admin';
	import ProjectCreateForm from '$lib/components/forms/ProjectCreateForm.svelte';
	import type { WorkStatus, ProjectTeamMember } from '$lib/graphql/queries/projects';

	// Create modal state
	let showCreateModal = $state(false);

	function handleCreateSuccess(projectId: string) {
		showCreateModal = false;
		goto(`/admin/projects/${projectId}`);
	}

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

	function isDispatched(teamMembers: ProjectTeamMember[]): boolean {
		return teamMembers.some((m) => m.teamProfile?.role === 'ADMIN');
	}

	function isAssigned(teamMembers: ProjectTeamMember[]): boolean {
		return teamMembers.some((m) => m.teamProfile?.role && m.teamProfile.role !== 'ADMIN');
	}

	function formatTeamMembers(teamMembers: ProjectTeamMember[]): string {
		const names = teamMembers
			.filter((m) => m.teamProfile?.role && m.teamProfile.role !== 'ADMIN')
			.map((m) => m.teamProfile?.fullName ?? '')
			.filter((name) => name !== '');

		if (names.length === 0) return '';
		if (names.length <= 2) return names.join(', ');
		return `${names.slice(0, 2).join(', ')} +${names.length - 2} other${names.length - 2 > 1 ? 's' : ''}`;
	}

	// Local search filter (client-side)
	let searchQuery = $state('');

	// Derived data
	let projects = $derived(data.projects.items ?? []);

	let filteredProjects = $derived(
		projects.filter((p) => {
			if (!searchQuery) return true;
			const query = searchQuery.toLowerCase();
			const name = p.name?.toLowerCase() ?? '';
			const customerName = p.customer?.name?.toLowerCase() ?? '';
			const address = p.formattedAddress?.toLowerCase() ?? '';
			return name.includes(query) || customerName.includes(query) || address.includes(query);
		})
	);

	function getStatusBadgeClass(status: WorkStatus): string {
		switch (status) {
			case 'SCHEDULED':
				return 'bg-accent2-100 text-accent2-800 dark:bg-accent2-900/30 dark:text-accent2-400';
			case 'IN_PROGRESS':
				return 'bg-accent-100 text-accent-800 dark:bg-accent-900/30 dark:text-accent-400';
			case 'COMPLETED':
				return 'bg-primary-100 text-primary-800 dark:bg-primary-900/30 dark:text-primary-400';
			case 'CANCELLED':
				return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400';
			default:
				return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300';
		}
	}

	function formatStatusLabel(status: WorkStatus): string {
		switch (status) {
			case 'IN_PROGRESS':
				return 'In Progress';
			default:
				return status.charAt(0) + status.slice(1).toLowerCase();
		}
	}

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

<svelte:head>
	<title>Projects - Admin - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		<!-- Header -->
		<AdminDashboardHeader
			title="Projects"
			subtitle="{data.projects.totalCount} projects for {data.month}"
		>
			{#snippet actions()}
				<button
					type="button"
					class="btn-primary flex w-full items-center justify-center gap-2 sm:w-auto sm:justify-start"
					onclick={() => (showCreateModal = true)}
				>
					<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="M12 4v16m8-8H4"
						/>
					</svg>
					Create Project
				</button>
			{/snippet}
		</AdminDashboardHeader>

		<!-- Month Selector and Status Tabs -->
		<div class="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
			<MonthSelector month={data.month} />
			<StatusTabs counts={data.statusCounts} currentStatus={data.status} />
		</div>

		<!-- Search -->
		<div class="mb-6">
			<div class="relative">
				<svg
					class="absolute top-1/2 left-3 h-5 w-5 -translate-y-1/2 text-theme-muted"
					fill="none"
					stroke="currentColor"
					viewBox="0 0 24 24"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="2"
						d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
					/>
				</svg>
				<input
					type="text"
					bind:value={searchQuery}
					placeholder="Search by project name, customer, or location..."
					class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme py-2 pr-4 pl-10 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
				/>
			</div>
		</div>

		<!-- Project List -->
		{#if filteredProjects.length > 0}
			<div class="mb-6 grid grid-cols-1 gap-4 md:grid-cols-2">
				{#each filteredProjects as project (project.id)}
					<a href="/admin/projects/{project.id}" class="block card-project">
						<!-- Project Name -->
						<h2 class="truncate text-lg font-semibold text-theme">
							{project.name}
						</h2>

						<!-- Customer -->
						{#if project.customer}
							<p class="truncate text-sm text-theme-secondary">
								{project.customer.name}
							</p>
						{/if}

						<!-- Location -->
						{#if project.formattedAddress}
							<p class="mt-1 truncate text-sm text-theme-muted">
								{project.formattedAddress}
							</p>
						{/if}

						<!-- Date and Team -->
						<div class="mt-3 flex items-center justify-between gap-2 text-sm">
							<span class="shrink-0 text-theme-secondary">{formatDate(project.date)}</span>
							{#if formatTeamMembers(project.teamMembers)}
								<span class="truncate text-theme-muted">
									{formatTeamMembers(project.teamMembers)}
								</span>
							{/if}
						</div>

						<!-- Badges -->
						<div class="mt-2 flex flex-wrap gap-1">
							<span
								class="inline-flex rounded-full px-2 py-0.5 text-xs font-semibold {getStatusBadgeClass(
									project.status
								)}"
							>
								{formatStatusLabel(project.status)}
							</span>
							{#if isDispatched(project.teamMembers)}
								<span
									class="inline-flex rounded-full bg-purple-100 px-2 py-0.5 text-xs font-semibold text-purple-800 dark:bg-purple-900/30 dark:text-purple-400"
								>
									Dispatched
								</span>
							{/if}
							{#if isAssigned(project.teamMembers)}
								<span
									class="inline-flex rounded-full bg-blue-100 px-2 py-0.5 text-xs font-semibold text-blue-800 dark:bg-blue-900/30 dark:text-blue-400"
								>
									Assigned
								</span>
							{/if}
						</div>
					</a>
				{/each}
			</div>

			<!-- Pagination -->
			<Pagination
				currentPage={data.page}
				totalCount={data.projects.totalCount}
				limit={data.limit}
				hasNextPage={data.projects.hasNextPage}
			/>
		{:else if searchQuery}
			<!-- No results with search -->
			<div class="rounded-lg border border-theme bg-theme-secondary py-12 text-center">
				<svg
					class="mx-auto h-12 w-12 text-theme-muted"
					fill="none"
					stroke="currentColor"
					viewBox="0 0 24 24"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="1.5"
						d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
					/>
				</svg>
				<h3 class="mt-4 text-lg font-medium text-theme">No projects found</h3>
				<p class="mt-2 text-theme-secondary">No projects match your search.</p>
				<button
					type="button"
					onclick={() => (searchQuery = '')}
					class="mt-4 text-primary-500 hover:text-primary-600"
				>
					Clear search
				</button>
			</div>
		{:else if data.projects.totalCount === 0}
			<!-- Empty state for month/status -->
			<div class="rounded-lg border border-theme bg-theme-secondary py-12 text-center">
				<svg
					class="mx-auto h-12 w-12 text-theme-muted"
					fill="none"
					stroke="currentColor"
					viewBox="0 0 24 24"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="1.5"
						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>
				<h3 class="mt-4 text-lg font-medium text-theme">No projects</h3>
				<p class="mt-2 text-theme-secondary">
					{#if data.status}
						No {formatStatusLabel(data.status).toLowerCase()} projects for this month.
					{:else}
						No projects scheduled for this month.
					{/if}
				</p>
			</div>
		{/if}
	</ContentContainer>
</div>

<!-- Create Project Modal -->
{#if showCreateModal}
	<div
		class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
		onclick={(e) => e.target === e.currentTarget && (showCreateModal = false)}
		onkeydown={(e) => e.key === 'Escape' && (showCreateModal = false)}
		role="dialog"
		aria-modal="true"
		tabindex="-1"
	>
		<div
			class="max-h-[90vh] w-full max-w-lg overflow-y-auto rounded-xl border border-theme bg-theme p-6 shadow-2xl"
		>
			<div class="mb-5 flex items-center justify-between">
				<h2 class="text-xl font-semibold text-theme">Create Project</h2>
				<button
					type="button"
					class="rounded-lg p-1 text-theme-muted hover:bg-theme-secondary hover:text-theme"
					onclick={() => (showCreateModal = false)}
					aria-label="Close"
				>
					<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="M6 18L18 6M6 6l12 12"
						/>
					</svg>
				</button>
			</div>
			<ProjectCreateForm
				onSuccess={handleCreateSuccess}
				onCancel={() => (showCreateModal = false)}
			/>
		</div>
	</div>
{/if}
