<script lang="ts">
	import type { PageData } from './$types';
	import { invalidateAll } from '$app/navigation';
	import { client } from '$lib/graphql/client';
	import { UPDATE_TEAM_PROFILE, UPDATE_CUSTOMER_PROFILE } from '$lib/graphql/mutations/profile';
	import { ContentContainer } from '$lib/components/layout';
	import { PageHeader, SectionHeader } from '$lib/components/admin';
	import { FormDrawer } from '$lib/components/drawers';
	import { formatDate } from '$lib/utils/date';
	import type { MyTeamProfile, MyCustomerProfile } from '$lib/graphql/queries/myProfile';
	import type { TeamRole, EntityStatus } from '$lib/graphql/queries/team';

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

	let profile = $derived(data.profile);

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

	// Form state
	let firstName = $state('');
	let lastName = $state('');
	let email = $state('');
	let phone = $state('');
	let loading = $state(false);
	let error = $state<string | null>(null);

	function isTeamProfile(p: typeof profile): p is MyTeamProfile {
		return p?.__typename === 'TeamProfileType';
	}

	function isCustomerProfile(p: typeof profile): p is MyCustomerProfile {
		return p?.__typename === 'CustomerProfileType';
	}

	function getStatusBadgeClass(status: EntityStatus): string {
		switch (status) {
			case 'ACTIVE':
				return 'badge-success';
			case 'INACTIVE':
				return 'badge-neutral';
			case 'PENDING':
				return 'badge-warning';
			default:
				return 'badge-neutral';
		}
	}

	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 'badge-neutral';
		}
	}

	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 handleEditProfile() {
		if (profile) {
			firstName = profile.firstName;
			lastName = profile.lastName;
			email = profile.email ?? '';
			phone = profile.phone ?? '';
		}
		drawerOpen = true;
	}

	function closeDrawer() {
		drawerOpen = false;
		error = null;
	}

	async function handleSubmit(event: SubmitEvent) {
		event.preventDefault();
		if (!profile) return;

		loading = true;
		error = null;

		try {
			const input = {
				firstName,
				lastName,
				email,
				phone
			};

			if (isTeamProfile(profile)) {
				await client.mutate({
					mutation: UPDATE_TEAM_PROFILE,
					variables: { id: profile.id, input }
				});
			} else {
				await client.mutate({
					mutation: UPDATE_CUSTOMER_PROFILE,
					variables: { id: profile.id, input }
				});
			}

			closeDrawer();
			await invalidateAll();
		} catch (err) {
			error = err instanceof Error ? err.message : 'An error occurred';
		} finally {
			loading = false;
		}
	}
</script>

<svelte:head>
	<title>My Profile - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer maxWidth="4xl">
		{#if profile}
			<PageHeader title="My Profile" colorScheme="primary">
				<span class={getStatusBadgeClass(profile.status)}>{profile.status}</span>
			</PageHeader>

			<div class="space-y-6">
				<!-- Profile Information -->
				<section
					class="overflow-hidden rounded-xl border border-primary-500/20 bg-theme-card shadow-theme-md"
				>
					<div
						class="border-b border-primary-500/20 bg-linear-to-r from-primary-500/10 to-transparent px-5 py-3"
					>
						<SectionHeader
							title="Profile Info"
							buttonText="Edit"
							buttonIcon="edit"
							onButtonClick={handleEditProfile}
						/>
					</div>
					<div class="grid grid-cols-1 gap-6 px-5 py-5 sm:grid-cols-2">
						<div>
							<p class="detail-label">First Name</p>
							<p class="text-theme">{profile.firstName}</p>
						</div>
						<div>
							<p class="detail-label">Last Name</p>
							<p class="text-theme">{profile.lastName}</p>
						</div>
						<div>
							<p class="detail-label">Email</p>
							<p class="text-theme">{profile.email || '—'}</p>
						</div>
						<div>
							<p class="detail-label">Phone</p>
							<p class="text-theme">{profile.phone || '—'}</p>
						</div>
					</div>
				</section>

				<!-- Role & Status (Team profiles only) -->
				{#if isTeamProfile(profile)}
					<section
						class="overflow-hidden rounded-xl border border-primary-500/20 bg-theme-card shadow-theme-md"
					>
						<div
							class="border-b border-primary-500/20 bg-linear-to-r from-primary-500/10 to-transparent px-5 py-3"
						>
							<SectionHeader title="Role & Access" />
						</div>
						<div class="grid grid-cols-1 gap-6 px-5 py-5 sm:grid-cols-2">
							<div>
								<p class="detail-label">Role</p>
								<span
									class="inline-flex rounded-full px-2.5 py-1 text-xs font-semibold {getRoleBadgeClass(
										profile.role
									)}"
								>
									{formatRole(profile.role)}
								</span>
							</div>
							<div>
								<p class="detail-label">Status</p>
								<span class={getStatusBadgeClass(profile.status)}>{profile.status}</span>
							</div>
						</div>
					</section>
				{/if}

				<!-- Associated Customers (Customer profiles only) -->
				{#if isCustomerProfile(profile) && profile.customers.length > 0}
					<section
						class="overflow-hidden rounded-xl border border-primary-500/20 bg-theme-card shadow-theme-md"
					>
						<div
							class="border-b border-primary-500/20 bg-linear-to-r from-primary-500/10 to-transparent px-5 py-3"
						>
							<SectionHeader title="Associated Customers" />
						</div>
						<div class="px-5 py-5">
							<ul class="space-y-2">
								{#each profile.customers as customer}
									<li class="text-theme">{customer.name}</li>
								{/each}
							</ul>
						</div>
					</section>
				{/if}

				<!-- Notes -->
				{#if profile.notes}
					<section
						class="overflow-hidden rounded-xl border border-primary-500/20 bg-theme-card shadow-theme-md"
					>
						<div
							class="border-b border-primary-500/20 bg-linear-to-r from-primary-500/10 to-transparent px-5 py-3"
						>
							<SectionHeader title="Notes" />
						</div>
						<div class="px-5 py-5">
							<p class="whitespace-pre-wrap text-theme">{profile.notes}</p>
						</div>
					</section>
				{/if}

				<!-- Account Information -->
				<section
					class="overflow-hidden rounded-xl border border-theme bg-theme-card shadow-theme-md"
				>
					<div class="bg-theme-secondary/50 border-b border-theme px-5 py-3">
						<SectionHeader title="Account Information" />
					</div>
					<div class="grid grid-cols-1 gap-6 px-5 py-5 sm:grid-cols-2">
						<div>
							<p class="detail-label">Account Type</p>
							<p class="text-theme">
								{isTeamProfile(profile) ? 'Team Member' : 'Customer'}
							</p>
						</div>
						<div>
							<p class="detail-label">Member Since</p>
							<p class="text-theme">{formatDate(profile.createdAt)}</p>
						</div>
						<div>
							<p class="detail-label">Last Updated</p>
							<p class="text-theme">{formatDate(profile.updatedAt)}</p>
						</div>
					</div>
				</section>
			</div>

			<!-- Edit Profile Drawer -->
			<FormDrawer open={drawerOpen} title="Edit Profile" onClose={closeDrawer}>
				<form onsubmit={handleSubmit} class="space-y-5">
					{#if error}
						<div
							class="rounded-lg border border-error-500/30 bg-error-50/50 p-3 dark:bg-error-950/30"
						>
							<p class="text-sm text-error-700 dark:text-error-400">{error}</p>
						</div>
					{/if}

					<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
						<label class="block">
							<span class="form-label">
								First Name <span class="required-indicator">*</span>
							</span>
							<input
								type="text"
								bind:value={firstName}
								class="input-base"
								required
								disabled={loading}
							/>
						</label>

						<label class="block">
							<span class="form-label">
								Last Name <span class="required-indicator">*</span>
							</span>
							<input
								type="text"
								bind:value={lastName}
								class="input-base"
								required
								disabled={loading}
							/>
						</label>
					</div>

					<label class="block">
						<span class="form-label">Email</span>
						<input type="email" bind:value={email} class="input-base" disabled={loading} />
					</label>

					<label class="block">
						<span class="form-label">Phone</span>
						<input
							type="tel"
							bind:value={phone}
							class="input-base"
							placeholder="(555) 123-4567"
							disabled={loading}
						/>
					</label>

					<div class="form-actions border-t border-theme pt-5">
						<button type="button" class="btn-cancel" onclick={closeDrawer} disabled={loading}>
							Cancel
						</button>
						<button type="submit" class="btn-submit" disabled={loading}>
							{#if loading}
								Saving...
							{:else}
								Save Changes
							{/if}
						</button>
					</div>
				</form>
			</FormDrawer>
		{:else}
			<div class="empty-state">
				<svg class="empty-state-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="1.5"
						d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
					/>
				</svg>
				<h2 class="empty-state-title">Profile not found</h2>
				<p class="empty-state-text">Unable to load your profile. Please try logging in again.</p>
				<a href="/login" class="mt-4 btn-primary">Login</a>
			</div>
		{/if}
	</ContentContainer>
</div>
