<script lang="ts">
	import type { PageData } from './$types';
	import ContentContainer from '$lib/components/layout/ContentContainer.svelte';
	import DeleteConfirmModal from '$lib/components/admin/DeleteConfirmModal.svelte';
	import TeamProfileForm from '$lib/components/admin/profiles/TeamProfileForm.svelte';
	import CustomerProfileForm from '$lib/components/admin/profiles/CustomerProfileForm.svelte';
	import { DeleteTeamProfileStore, DeleteCustomerProfileStore } from '$houdini';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import { invalidateAll } from '$app/navigation';

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

	let teamProfiles = $derived(data.profiles?.data?.teamProfiles ?? []);
	let customerProfiles = $derived(data.profiles?.data?.customerProfiles ?? []);
	let customers = $derived(data.customers?.data?.customers ?? []);

	// Tab state
	type TabType = 'team' | 'customer';
	let activeTab = $state<TabType>('team');

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

	// Filtered lists
	let filteredTeamProfiles = $derived(
		teamProfiles.filter(
			(p) =>
				p.fullName.toLowerCase().includes(searchQuery.toLowerCase()) ||
				(p.email?.toLowerCase().includes(searchQuery.toLowerCase()) ?? false) ||
				p.role.toLowerCase().includes(searchQuery.toLowerCase())
		)
	);

	let filteredCustomerProfiles = $derived(
		customerProfiles.filter(
			(p) =>
				p.fullName.toLowerCase().includes(searchQuery.toLowerCase()) ||
				(p.email?.toLowerCase().includes(searchQuery.toLowerCase()) ?? false) ||
				p.customers.some((c) => c.name.toLowerCase().includes(searchQuery.toLowerCase()))
		)
	);

	// Edit state
	let editingTeamProfile = $state<(typeof teamProfiles)[0] | null>(null);
	let editingCustomerProfile = $state<(typeof customerProfiles)[0] | null>(null);

	// Delete state
	let showDeleteModal = $state(false);
	let isDeleting = $state(false);
	let profileToDelete = $state<{ id: string; name: string; type: 'team' | 'customer' } | null>(
		null
	);

	const deleteTeamStore = new DeleteTeamProfileStore();
	const deleteCustomerStore = new DeleteCustomerProfileStore();

	// Status helpers
	function getStatusClasses(status: string): string {
		switch (status) {
			case 'ACTIVE':
				return 'bg-success-500/10 text-success-600 dark:text-success-400';
			case 'INACTIVE':
				return 'bg-gray-500/10 text-gray-600 dark:text-gray-400';
			case 'PENDING':
				return 'bg-warning-500/10 text-warning-600 dark:text-warning-400';
			default:
				return 'bg-gray-500/10 text-gray-600 dark:text-gray-400';
		}
	}

	function getStatusLabel(status: string): string {
		switch (status) {
			case 'ACTIVE':
				return 'Active';
			case 'INACTIVE':
				return 'Inactive';
			case 'PENDING':
				return 'Pending';
			default:
				return status;
		}
	}

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

	// Form handlers
	function showCreateTeamForm() {
		offCanvas.showRight({
			title: 'Create Team Member',
			content: createTeamFormContent
		});
	}

	function showCreateCustomerForm() {
		offCanvas.showRight({
			title: 'Create Customer Profile',
			content: createCustomerFormContent
		});
	}

	function showEditTeamForm(profile: (typeof teamProfiles)[0]) {
		editingTeamProfile = profile;
		offCanvas.showRight({
			title: 'Edit Team Member',
			content: editTeamFormContent
		});
	}

	function showEditCustomerForm(profile: (typeof customerProfiles)[0]) {
		editingCustomerProfile = profile;
		offCanvas.showRight({
			title: 'Edit Customer Profile',
			content: editCustomerFormContent
		});
	}

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

	function promptDelete(id: string, name: string, type: 'team' | 'customer') {
		profileToDelete = { id, name, type };
		showDeleteModal = true;
	}

	async function handleDelete() {
		if (!profileToDelete) return;
		isDeleting = true;

		try {
			if (profileToDelete.type === 'team') {
				await deleteTeamStore.mutate({ id: profileToDelete.id });
			} else {
				await deleteCustomerStore.mutate({ id: profileToDelete.id });
			}
			await invalidateAll();
		} catch (err) {
			console.error('Failed to delete profile:', err);
		} finally {
			isDeleting = false;
			showDeleteModal = false;
			profileToDelete = null;
		}
	}
</script>

{#snippet createTeamFormContent()}
	<TeamProfileForm onSuccess={handleSuccess} />
{/snippet}

{#snippet createCustomerFormContent()}
	<CustomerProfileForm {customers} onSuccess={handleSuccess} />
{/snippet}

{#snippet editTeamFormContent()}
	{#if editingTeamProfile}
		<TeamProfileForm profile={editingTeamProfile} onSuccess={handleSuccess} />
	{/if}
{/snippet}

{#snippet editCustomerFormContent()}
	{#if editingCustomerProfile}
		<CustomerProfileForm profile={editingCustomerProfile} {customers} onSuccess={handleSuccess} />
	{/if}
{/snippet}

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

<div class="py-8">
	<ContentContainer>
		<div class="mb-8">
			<div class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
				<div class="flex items-start gap-4">
					<a
						href="/admin"
						class="rounded-lg p-1 text-theme-muted hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
						aria-label="Go back"
					>
						<svg class="h-5 w-5" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M15 19l-7-7 7-7"
							/>
						</svg>
					</a>
					<div>
						<h1 class="text-2xl font-bold text-accent4-600 md:text-3xl dark:text-accent4-400">
							Profiles
						</h1>
						<p class="mt-2 text-theme-secondary">Manage team members and customer profiles.</p>
					</div>
				</div>
				<button
					type="button"
					onclick={() => (activeTab === 'team' ? showCreateTeamForm() : showCreateCustomerForm())}
					class="hidden items-center gap-2 rounded-lg bg-primary-500 px-4 py-2 text-white transition-colors hover:bg-primary-600 sm:inline-flex"
				>
					<svg class="h-5 w-5" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M12 4v16m8-8H4"
						/>
					</svg>
					<span>Add {activeTab === 'team' ? 'Team Member' : 'Customer Profile'}</span>
				</button>
			</div>
		</div>

		<!-- Tabs -->
		<div class="mb-6 flex items-center justify-between gap-4">
			<div class="flex items-center rounded-lg border border-theme bg-theme p-1">
				<button
					onclick={() => (activeTab = 'team')}
					class="flex items-center gap-1.5 rounded-md px-4 py-2 text-sm font-medium transition-colors {activeTab ===
					'team'
						? 'bg-accent4-500/10 text-accent4-600 shadow-sm dark:text-accent4-400'
						: 'text-theme-muted hover:text-theme'}"
				>
					<svg class="h-4 w-4" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
						<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>
					Team
					<span class="rounded-full bg-accent4-500 px-1.5 py-0.5 text-xs text-white">
						{teamProfiles.length}
					</span>
				</button>
				<button
					onclick={() => (activeTab = 'customer')}
					class="flex items-center gap-1.5 rounded-md px-4 py-2 text-sm font-medium transition-colors {activeTab ===
					'customer'
						? 'bg-accent4-500/10 text-accent4-600 shadow-sm dark:text-accent4-400'
						: 'text-theme-muted hover:text-theme'}"
				>
					<svg class="h-4 w-4" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							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>
					Customer
					<span class="rounded-full bg-accent4-500 px-1.5 py-0.5 text-xs text-white">
						{customerProfiles.length}
					</span>
				</button>
			</div>
		</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"
					style="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 {activeTab === 'team' ? 'team members' : 'customer profiles'}..."
					class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme-card py-2 pr-4 pl-10 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500"
				/>
			</div>
		</div>

		<!-- Team Profiles Tab -->
		{#if activeTab === 'team'}
			{#if filteredTeamProfiles.length > 0}
				<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
					{#each filteredTeamProfiles as profile (profile.id)}
						<div class="flex min-w-0 items-center justify-between card-profile">
							<div class="min-w-0 flex-1">
								<div class="mb-1 flex items-center gap-2">
									<h3 class="truncate font-semibold text-theme">{profile.fullName}</h3>
									<span
										class={`inline-flex flex-shrink-0 items-center rounded-full px-2 py-0.5 text-xs font-medium ${getStatusClasses(profile.status)}`}
									>
										{getStatusLabel(profile.status)}
									</span>
								</div>
								<p class="text-sm text-theme-secondary">{getRoleLabel(profile.role)}</p>
								{#if profile.email}
									<p class="truncate text-sm text-theme-muted">{profile.email}</p>
								{/if}
								{#if profile.phone}
									<p class="truncate text-sm text-theme-muted">{profile.phone}</p>
								{/if}
							</div>
							<div class="flex flex-shrink-0 items-center gap-2">
								<button
									onclick={() => showEditTeamForm(profile)}
									class="rounded-lg bg-accent4-500/10 px-3 py-1.5 text-sm font-medium text-accent4-600 transition-colors hover:bg-accent4-500/20 dark:text-accent4-400"
								>
									Edit
								</button>
								<button
									onclick={() => promptDelete(profile.id, profile.fullName, 'team')}
									class="rounded-lg bg-error-500/10 p-1.5 text-error-600 transition-colors hover:bg-error-500/20 dark:text-error-400"
									title="Delete"
								>
									<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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
										/>
									</svg>
								</button>
							</div>
						</div>
					{/each}
				</div>
			{:else if searchQuery}
				<div class="empty-state">
					<svg
						class="empty-state-icon"
						style="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>
					<h2 class="empty-state-title">No team members found</h2>
					<p class="empty-state-text">
						No team members match "{searchQuery}". Try a different search term.
					</p>
				</div>
			{:else}
				<div class="empty-state">
					<svg
						class="empty-state-icon"
						style="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>
					<h2 class="empty-state-title">No team members yet</h2>
					<p class="empty-state-text">Get started by adding your first team member.</p>
					<button
						type="button"
						onclick={showCreateTeamForm}
						class="mt-4 inline-flex items-center gap-2 rounded-lg bg-primary-500 px-4 py-2 text-white transition-colors hover:bg-primary-600"
					>
						<svg class="h-5 w-5" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M12 4v16m8-8H4"
							/>
						</svg>
						<span>Add Team Member</span>
					</button>
				</div>
			{/if}
		{:else}
			<!-- Customer Profiles Tab -->
			{#if filteredCustomerProfiles.length > 0}
				<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
					{#each filteredCustomerProfiles as profile (profile.id)}
						<div class="flex min-w-0 items-center justify-between card-profile">
							<div class="min-w-0 flex-1">
								<div class="mb-1 flex items-center gap-2">
									<h3 class="truncate font-semibold text-theme">{profile.fullName}</h3>
									<span
										class={`inline-flex flex-shrink-0 items-center rounded-full px-2 py-0.5 text-xs font-medium ${getStatusClasses(profile.status)}`}
									>
										{getStatusLabel(profile.status)}
									</span>
								</div>
								{#if profile.customers.length > 0}
									<p class="truncate text-sm text-theme-secondary">
										{profile.customers.map((c) => c.name).join(', ')}
									</p>
								{:else}
									<p class="text-sm text-theme-muted">No linked customers</p>
								{/if}
								{#if profile.email}
									<p class="truncate text-sm text-theme-muted">{profile.email}</p>
								{/if}
								{#if profile.phone}
									<p class="truncate text-sm text-theme-muted">{profile.phone}</p>
								{/if}
							</div>
							<div class="flex flex-shrink-0 items-center gap-2">
								<button
									onclick={() => showEditCustomerForm(profile)}
									class="rounded-lg bg-accent4-500/10 px-3 py-1.5 text-sm font-medium text-accent4-600 transition-colors hover:bg-accent4-500/20 dark:text-accent4-400"
								>
									Edit
								</button>
								<button
									onclick={() => promptDelete(profile.id, profile.fullName, 'customer')}
									class="rounded-lg bg-error-500/10 p-1.5 text-error-600 transition-colors hover:bg-error-500/20 dark:text-error-400"
									title="Delete"
								>
									<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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
										/>
									</svg>
								</button>
							</div>
						</div>
					{/each}
				</div>
			{:else if searchQuery}
				<div class="empty-state">
					<svg
						class="empty-state-icon"
						style="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>
					<h2 class="empty-state-title">No customer profiles found</h2>
					<p class="empty-state-text">
						No customer profiles match "{searchQuery}". Try a different search term.
					</p>
				</div>
			{:else}
				<div class="empty-state">
					<svg
						class="empty-state-icon"
						style="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>
					<h2 class="empty-state-title">No customer profiles yet</h2>
					<p class="empty-state-text">Get started by adding your first customer profile.</p>
					<button
						type="button"
						onclick={showCreateCustomerForm}
						class="mt-4 inline-flex items-center gap-2 rounded-lg bg-primary-500 px-4 py-2 text-white transition-colors hover:bg-primary-600"
					>
						<svg class="h-5 w-5" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M12 4v16m8-8H4"
							/>
						</svg>
						<span>Add Customer Profile</span>
					</button>
				</div>
			{/if}
		{/if}
	</ContentContainer>
</div>

<!-- Mobile FAB -->
<button
	type="button"
	onclick={() => (activeTab === 'team' ? showCreateTeamForm() : showCreateCustomerForm())}
	class="fixed right-4 bottom-20 z-30 flex h-14 w-14 items-center justify-center rounded-full bg-primary-500 text-white shadow-lg transition-colors hover:bg-primary-600 sm:hidden"
	aria-label="Add {activeTab === 'team' ? 'team member' : 'customer profile'}"
>
	<svg class="h-6 w-6" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
		<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
	</svg>
</button>

<DeleteConfirmModal
	bind:open={showDeleteModal}
	title="Delete {profileToDelete?.type === 'team' ? 'Team Member' : 'Customer Profile'}"
	message="Are you sure you want to delete {profileToDelete?.name}? This action cannot be undone."
	onconfirm={handleDelete}
	oncancel={() => {}}
	loading={isDeleting}
/>
