<script lang="ts">
	import type { PageData } from './$types';
	import { goto, invalidateAll } from '$app/navigation';
	import { ContentContainer } from '$lib/components/layout';
	import { FormDrawer } from '$lib/components/drawers';
	import { TeamProfileCreateForm, CustomerProfileCreateForm } from '$lib/components/forms';
	import { IconPlus } from '$lib/components/icons';
	import { AdminDashboardHeader } from '$lib/components/admin';
	import type { TeamProfile, TeamRole, EntityStatus } from '$lib/graphql/queries/team';
	import type { CustomerProfile } from '$lib/graphql/queries/customerProfile';

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

	// Tab state - synced with URL
	let activeTab = $state(data.tab as 'team' | 'customer');

	function setTab(tab: 'team' | 'customer') {
		activeTab = tab;
		const url = new URL(window.location.href);
		url.searchParams.set('tab', tab);
		goto(url.toString(), { replaceState: true, noScroll: true });
	}

	// Reactive state for filters
	let searchQuery = $state('');
	let statusFilter = $state<'ALL' | EntityStatus>('ALL');
	let roleFilter = $state<'ALL' | TeamRole>('ALL');

	// Drawer state
	let createDrawerOpen = $state(false);

	// Derived data
	let teamProfiles = $derived((data.teamProfiles ?? []) as TeamProfile[]);
	let customerProfiles = $derived((data.customerProfiles ?? []) as CustomerProfile[]);

	// Filtered team profiles
	let filteredTeamProfiles = $derived(
		teamProfiles.filter((p) => {
			if (searchQuery) {
				const query = searchQuery.toLowerCase();
				const matchesName = p.fullName.toLowerCase().includes(query);
				const matchesEmail = p.email?.toLowerCase().includes(query) ?? false;
				if (!matchesName && !matchesEmail) return false;
			}
			if (statusFilter !== 'ALL' && p.status !== statusFilter) return false;
			if (roleFilter !== 'ALL' && p.role !== roleFilter) return false;
			return true;
		})
	);

	// Filtered customer profiles
	let filteredCustomerProfiles = $derived(
		customerProfiles.filter((p) => {
			if (searchQuery) {
				const query = searchQuery.toLowerCase();
				const matchesName = p.fullName.toLowerCase().includes(query);
				const matchesEmail = p.email?.toLowerCase().includes(query) ?? false;
				if (!matchesName && !matchesEmail) return false;
			}
			if (statusFilter !== 'ALL' && p.status !== statusFilter) return false;
			return true;
		})
	);

	// Statistics
	let teamTotal = $derived(teamProfiles.length);
	let teamFiltered = $derived(filteredTeamProfiles.length);
	let customerTotal = $derived(customerProfiles.length);
	let customerFiltered = $derived(filteredCustomerProfiles.length);

	function clearFilters() {
		searchQuery = '';
		statusFilter = 'ALL';
		roleFilter = 'ALL';
	}

	function getStatusBadgeClass(status: EntityStatus): string {
		switch (status) {
			case 'ACTIVE':
				return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400';
			case 'INACTIVE':
				return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300';
			case 'PENDING':
				return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400';
			default:
				return 'bg-gray-100 text-gray-800';
		}
	}

	function getRoleBadgeClass(role: TeamRole): string {
		switch (role) {
			case 'ADMIN':
				return 'bg-accent5-100 text-accent5-800 dark:bg-accent5-900/30 dark:text-accent5-400';
			case 'TEAM_LEADER':
				return 'bg-accent-100 text-accent-800 dark:bg-accent-900/30 dark:text-accent-400';
			case 'TEAM_MEMBER':
				return 'bg-secondary-100 text-secondary-800 dark:bg-secondary-900/30 dark:text-secondary-400';
			default:
				return 'bg-gray-100 text-gray-800';
		}
	}

	function formatRole(role: TeamRole): string {
		switch (role) {
			case 'ADMIN':
				return 'Admin';
			case 'TEAM_LEADER':
				return 'Team Leader';
			case 'TEAM_MEMBER':
				return 'Team Member';
			default:
				return role;
		}
	}

	function handleCreate() {
		createDrawerOpen = true;
	}

	function closeDrawer() {
		createDrawerOpen = false;
	}

	async function handleTeamCreateSuccess(profileId: string) {
		closeDrawer();
		await invalidateAll();
		goto(`/admin/profiles/${profileId}`);
	}

	async function handleCustomerCreateSuccess(profileId: string) {
		closeDrawer();
		await invalidateAll();
		goto(`/admin/profiles/customer/${profileId}`);
	}
</script>

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

<div class="py-8">
	<ContentContainer>
		<!-- Header -->
		<AdminDashboardHeader title="Profiles">
			{#snippet subtitleSnippet()}
				{#if activeTab === 'team'}
					{#if statusFilter === 'ALL' && roleFilter === 'ALL'}
						{teamTotal} team member{teamTotal !== 1 ? 's' : ''}
					{:else}
						{teamFiltered} of {teamTotal} team members
					{/if}
				{:else if statusFilter === 'ALL'}
					{customerTotal} customer profile{customerTotal !== 1 ? 's' : ''}
				{:else}
					{customerFiltered} of {customerTotal} customer profiles
				{/if}
			{/snippet}
			{#snippet actions()}
				<button type="button" class="btn-primary flex items-center gap-2" onclick={handleCreate}>
					<IconPlus />
					<span>Create Profile</span>
				</button>
			{/snippet}
		</AdminDashboardHeader>

		<!-- Tabs -->
		<div class="mb-6 border-b border-theme">
			<nav class="-mb-px flex gap-4" aria-label="Profile type tabs">
				<button
					type="button"
					onclick={() => setTab('team')}
					class="border-b-2 px-1 py-3 text-sm font-medium transition-colors {activeTab === 'team'
						? 'border-accent5-500 text-accent5-600 dark:text-accent5-400'
						: 'hover:border-theme-muted border-transparent text-theme-secondary hover:text-theme'}"
				>
					Team ({teamTotal})
				</button>
				<button
					type="button"
					onclick={() => setTab('customer')}
					class="border-b-2 px-1 py-3 text-sm font-medium transition-colors {activeTab ===
					'customer'
						? 'border-accent3-500 text-accent3-600 dark:text-accent3-400'
						: 'hover:border-theme-muted border-transparent text-theme-secondary hover:text-theme'}"
				>
					Customer ({customerTotal})
				</button>
			</nav>
		</div>

		<!-- Filters -->
		<div class="mb-6 space-y-4">
			<!-- Search -->
			<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 name or email..."
					class="input-base w-full py-2 pr-4 pl-10"
				/>
			</div>

			<!-- Filter Controls -->
			<div class="flex flex-wrap items-center gap-4">
				<!-- Status Filter -->
				<label class="flex items-center gap-2">
					<span class="text-sm font-medium text-theme-secondary">Status:</span>
					<select bind:value={statusFilter} class="select-base px-3 py-1.5 text-sm">
						<option value="ALL">All Statuses</option>
						<option value="ACTIVE">Active</option>
						<option value="INACTIVE">Inactive</option>
						<option value="PENDING">Pending</option>
					</select>
				</label>

				<!-- Role Filter (Team only) -->
				{#if activeTab === 'team'}
					<label class="flex items-center gap-2">
						<span class="text-sm font-medium text-theme-secondary">Role:</span>
						<select bind:value={roleFilter} class="select-base px-3 py-1.5 text-sm">
							<option value="ALL">All Roles</option>
							<option value="ADMIN">Admin</option>
							<option value="TEAM_LEADER">Team Leader</option>
							<option value="TEAM_MEMBER">Team Member</option>
						</select>
					</label>
				{/if}

				<!-- Clear Filters -->
				{#if searchQuery || statusFilter !== 'ALL' || (activeTab === 'team' && roleFilter !== 'ALL')}
					<button
						type="button"
						onclick={clearFilters}
						class="text-sm text-accent4-600 hover:text-accent4-700 dark:text-accent4-400"
					>
						Clear filters
					</button>
				{/if}

				<!-- Results Count -->
				<span class="ml-auto text-sm text-theme-muted">
					{#if activeTab === 'team'}
						Showing {teamFiltered} of {teamTotal}
					{:else}
						Showing {customerFiltered} of {customerTotal}
					{/if}
				</span>
			</div>
		</div>

		<!-- Team Profiles List -->
		{#if activeTab === 'team'}
			{#if filteredTeamProfiles.length > 0}
				<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
					{#each filteredTeamProfiles as profile (profile.id)}
						<a href="/admin/profiles/{profile.id}" class="flex flex-col card-team">
							<div class="flex items-start justify-between">
								<div class="min-w-0 flex-1">
									<h2 class="truncate text-lg font-semibold text-theme">{profile.fullName}</h2>
									{#if profile.email}
										<p class="mt-0.5 truncate text-sm text-theme-secondary">{profile.email}</p>
									{/if}
								</div>
								<svg
									class="ml-2 h-5 w-5 shrink-0 text-theme-muted"
									fill="none"
									stroke="currentColor"
									viewBox="0 0 24 24"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M9 5l7 7-7 7"
									/>
								</svg>
							</div>
							<div class="mt-3 flex flex-wrap items-center gap-2">
								<span
									class="inline-flex rounded-full px-2 py-0.5 text-xs font-semibold {getRoleBadgeClass(
										profile.role
									)}"
								>
									{formatRole(profile.role)}
								</span>
								<span
									class="inline-flex rounded-full px-2 py-0.5 text-xs font-semibold {getStatusBadgeClass(
										profile.status
									)}"
								>
									{profile.status}
								</span>
							</div>
							{#if profile.phone}
								<p class="mt-2 text-sm text-theme-muted">{profile.phone}</p>
							{/if}
						</a>
					{/each}
				</div>
			{:else if searchQuery || statusFilter !== 'ALL' || roleFilter !== 'ALL'}
				<!-- No results with filters -->
				<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 profiles found</h3>
					<p class="mt-2 text-theme-secondary">No team members match your current filters.</p>
					<button
						type="button"
						onclick={clearFilters}
						class="mt-4 text-accent4-600 hover:text-accent4-700 dark:text-accent4-400"
					>
						Clear all filters
					</button>
				</div>
			{:else}
				<!-- Empty state -->
				<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="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>
					<h3 class="mt-4 text-lg font-medium text-theme">No team profiles</h3>
					<p class="mt-2 text-theme-secondary">Create a profile by linking a Kratos identity.</p>
					<button type="button" class="mt-4 btn-primary" onclick={handleCreate}>
						Create Profile
					</button>
				</div>
			{/if}
		{/if}

		<!-- Customer Profiles List -->
		{#if activeTab === 'customer'}
			{#if filteredCustomerProfiles.length > 0}
				<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
					{#each filteredCustomerProfiles as profile (profile.id)}
						<a href="/admin/profiles/customer/{profile.id}" class="flex flex-col card-customer">
							<div class="flex items-start justify-between">
								<div class="min-w-0 flex-1">
									<h2 class="truncate text-lg font-semibold text-theme">{profile.fullName}</h2>
									{#if profile.email}
										<p class="mt-0.5 truncate text-sm text-theme-secondary">{profile.email}</p>
									{/if}
								</div>
								<svg
									class="ml-2 h-5 w-5 shrink-0 text-theme-muted"
									fill="none"
									stroke="currentColor"
									viewBox="0 0 24 24"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M9 5l7 7-7 7"
									/>
								</svg>
							</div>
							<div class="mt-3 flex flex-wrap items-center gap-2">
								<span
									class="inline-flex rounded-full px-2 py-0.5 text-xs font-semibold {getStatusBadgeClass(
										profile.status
									)}"
								>
									{profile.status}
								</span>
							</div>
							{#if profile.phone}
								<p class="mt-2 text-sm text-theme-muted">{profile.phone}</p>
							{/if}
						</a>
					{/each}
				</div>
			{:else if searchQuery || statusFilter !== 'ALL'}
				<!-- No results with filters -->
				<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 profiles found</h3>
					<p class="mt-2 text-theme-secondary">No customer profiles match your current filters.</p>
					<button
						type="button"
						onclick={clearFilters}
						class="mt-4 text-accent4-600 hover:text-accent4-700 dark:text-accent4-400"
					>
						Clear all filters
					</button>
				</div>
			{:else}
				<!-- Empty state -->
				<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="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
						/>
					</svg>
					<h3 class="mt-4 text-lg font-medium text-theme">No customer profiles</h3>
					<p class="mt-2 text-theme-secondary">Create a profile by linking a Kratos identity.</p>
					<button type="button" class="mt-4 btn-primary" onclick={handleCreate}>
						Create Profile
					</button>
				</div>
			{/if}
		{/if}
	</ContentContainer>

	<!-- Create Drawer - shows different form based on active tab -->
	<FormDrawer
		open={createDrawerOpen}
		title={activeTab === 'team' ? 'Create Team Profile' : 'Create Customer Profile'}
		onClose={closeDrawer}
	>
		{#if activeTab === 'team'}
			<TeamProfileCreateForm onSuccess={handleTeamCreateSuccess} onCancel={closeDrawer} />
		{:else}
			<CustomerProfileCreateForm onSuccess={handleCustomerCreateSuccess} onCancel={closeDrawer} />
		{/if}
	</FormDrawer>
</div>
