<script lang="ts">
	import { onMount } from 'svelte';
	import PageHeader from '$lib/components/layout/PageHeader.svelte';
	import DataTable from '$lib/components/common/DataTable.svelte';
	import FilterBar from '$lib/components/common/FilterBar.svelte';
	import LoadingState from '$lib/components/common/LoadingState.svelte';
	import EmptyState from '$lib/components/common/EmptyState.svelte';
	import { Plus, X, AlertCircle } from 'lucide-svelte';
	import { teamMemberService, formatHourlyRateWithUnit, type TeamMember, type CreateTeamMemberRequest } from '$lib/services/teamMemberService';
	import { api } from '$lib/services/api';

	// State
	let data = $state<TeamMember[]>([]);
	let loading = $state(true);
	let error = $state<string | null>(null);
	let search = $state('');
	let statusFilter = $state('all');
	let showModal = $state(false);
	let editingMember = $state<TeamMember | null>(null);
	let deleteConfirmMember = $state<TeamMember | null>(null);
	let formLoading = $state(false);
	let formError = $state<string | null>(null);
	let roles = $state<{ id: number; name: string }[]>([]);

	// Form state
	let formData = $state<CreateTeamMemberRequest>({
		name: '',
		role_id: 0, // Will be set from roles after load
		hourly_rate: 0,
		active: true
	});

	import type { ColumnDef } from '@tanstack/table-core';

	const columns: ColumnDef<TeamMember>[] = [
		{ accessorKey: 'name', header: 'Name' },
		{ 
			accessorKey: 'role', 
			header: 'Role',
			cell: (info) => info.row.original.role?.name || '-'
		},
		{ 
			accessorKey: 'hourly_rate', 
			header: 'Hourly Rate',
			cell: (info) => formatHourlyRateWithUnit(info.row.original.hourly_rate)
		},
		{ 
			accessorKey: 'active', 
			header: 'Status',
			cell: (info) => getStatusBadge(info.row.original.active)
		}
	];

	onMount(async () => {
		await Promise.all([loadTeamMembers(), loadRoles()]);
	});

	async function loadTeamMembers() {
		try {
			loading = true;
			error = null;
			const activeFilter = statusFilter === 'all' ? undefined : statusFilter === 'active';
			data = await teamMemberService.getAll(activeFilter);
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to load team members';
			console.error('Error loading team members:', err);
		} finally {
			loading = false;
		}
	}

	async function loadRoles() {
		try {
			// Fetch roles from API endpoint
			roles = await api.get<{ id: number; name: string }[]>('/roles');
		} catch (err) {
			console.error('Error loading roles:', err);
			// Fallback to empty array - form should not submit without valid roles
			roles = [];
		}
	}

	function handleCreate() {
		editingMember = null;
		// Default to first role if available
		const defaultRoleId = roles.length > 0 ? roles[0].id : 0;
		formData = { name: '', role_id: defaultRoleId, hourly_rate: 0, active: true };
		formError = null;
		showModal = true;
	}

	function handleEdit(row: TeamMember) {
		editingMember = row;
		formData = {
			name: row.name,
			role_id: row.role_id,
			hourly_rate: parseFloat(row.hourly_rate),
			active: row.active
		};
		formError = null;
		showModal = true;
	}

	function handleDeleteClick(row: TeamMember, event: Event) {
		event.stopPropagation();
		deleteConfirmMember = row;
	}

	async function handleSubmit() {
		try {
			formLoading = true;
			formError = null;

			// Validate roles are loaded
			if (roles.length === 0) {
				formError = 'Roles not loaded. Please refresh the page.';
				return;
			}

			if (!formData.role_id || formData.role_id === 0) {
				formError = 'Please select a valid role.';
				return;
			}

			if (editingMember) {
				await teamMemberService.update(editingMember.id, formData);
			} else {
				await teamMemberService.create(formData);
			}

			showModal = false;
			await loadTeamMembers();
		} catch (err) {
			const apiError = err as { message?: string; data?: { errors?: Record<string, string[]> } };
			if (apiError.data?.errors) {
				const errors = Object.entries(apiError.data.errors)
					.map(([field, msgs]) => `${field}: ${msgs.join(', ')}`)
					.join('; ');
				formError = errors;
			} else {
				formError = apiError.message || 'An error occurred';
			}
		} finally {
			formLoading = false;
		}
	}

	async function handleConfirmDelete() {
		if (!deleteConfirmMember) return;

		try {
			formLoading = true;
			await teamMemberService.delete(deleteConfirmMember.id);
			deleteConfirmMember = null;
			await loadTeamMembers();
		} catch (err) {
			const apiError = err as { message?: string; suggestion?: string };
			alert(apiError.message || 'Failed to delete team member');
		} finally {
			formLoading = false;
		}
	}

	function closeModal() {
		showModal = false;
		editingMember = null;
		formError = null;
	}

	function closeDeleteModal() {
		deleteConfirmMember = null;
	}

	function getStatusBadge(active: boolean) {
		return active 
			? '<span class="badge badge-success badge-sm">Active</span>'
			: '<span class="badge badge-ghost badge-sm">Inactive</span>';
	}

	// Reactive filtered data
	let filteredData = $derived(data.filter(m => {
		const matchesSearch = m.name.toLowerCase().includes(search.toLowerCase());
		const matchesStatus = statusFilter === 'all' || 
			(statusFilter === 'active' && m.active) ||
			(statusFilter === 'inactive' && !m.active);
		return matchesSearch && matchesStatus;
	}));

	// Reload when status filter changes
	$effect(() => {
		if (statusFilter !== undefined) {
			loadTeamMembers();
		}
	});
</script>

<svelte:head>
	<title>Team Members | Headroom</title>
</svelte:head>

<PageHeader title="Team Members" description="Manage your team roster">
	{#snippet children()}
		<button class="btn btn-primary btn-sm gap-2" onclick={handleCreate}>
			<Plus size={16} />
			Add Member
		</button>
	{/snippet}
</PageHeader>

<FilterBar 
	searchValue={search}
	searchPlaceholder="Search team members..."
	onSearchChange={(v) => search = v}
>
	{#snippet children()}
		<select class="select select-sm" bind:value={statusFilter}>
			<option value="all">All Status</option>
			<option value="active">Active</option>
			<option value="inactive">Inactive</option>
		</select>
	{/snippet}
</FilterBar>

{#if loading}
	<LoadingState />
{:else if error}
	<div class="alert alert-error">
		<AlertCircle size={20} />
		<span>{error}</span>
	</div>
{:else if data.length === 0}
	<EmptyState 
		title="No team members"
		description="Add your first team member to get started."
	>
		{#snippet children()}
			<button class="btn btn-primary" onclick={handleCreate}>
				<Plus size={16} />
				Add Member
			</button>
		{/snippet}
	</EmptyState>
{:else}
	<DataTable 
		data={filteredData}
		{columns}
		loading={false}
		emptyTitle="No matching team members"
		emptyDescription="Try adjusting your search or filter."
		onRowClick={handleEdit}
	/>
{/if}

<!-- Create/Edit Modal -->
{#if showModal}
<div class="modal modal-open">
	<div class="modal-box max-w-lg">
		<div class="flex justify-between items-center mb-4">
			<h3 class="font-bold text-lg">{editingMember ? 'Edit Team Member' : 'Add Team Member'}</h3>
			<button class="btn btn-ghost btn-sm btn-circle" onclick={closeModal}>
				<X size={18} />
			</button>
		</div>

		{#if formError}
			<div class="alert alert-error mb-4 text-sm">
				<AlertCircle size={16} />
				<span>{formError}</span>
			</div>
		{/if}

		<form onsubmit={(e) => { e.preventDefault(); handleSubmit(); }}>
			<!-- Name Field - Horizontal Layout -->
			<div class="form-control mb-4 flex flex-row items-center gap-4">
				<label class="label w-28 shrink-0" for="name">
					<span class="label-text font-medium">Name</span>
				</label>
				<input 
					type="text" 
					id="name"
					class="input input-bordered flex-1" 
					bind:value={formData.name}
					placeholder="Enter name"
					required
				/>
			</div>

			<!-- Role Field - Horizontal Layout -->
			<div class="form-control mb-4 flex flex-row items-center gap-4">
				<label class="label w-28 shrink-0" for="role">
					<span class="label-text font-medium">Role</span>
				</label>
				<select 
					id="role"
					class="select select-bordered flex-1" 
					bind:value={formData.role_id}
					required
				>
					{#each roles as role}
						<option value={role.id}>{role.name}</option>
					{/each}
				</select>
			</div>

			<!-- Hourly Rate Field - Horizontal Layout -->
			<div class="form-control mb-4 flex flex-row items-center gap-4">
				<label class="label w-28 shrink-0" for="hourly_rate">
					<span class="label-text font-medium">Hourly Rate</span>
				</label>
				<div class="flex-1 relative">
					<span class="absolute left-3 top-1/2 -translate-y-1/2 text-base-content/50">$</span>
					<input 
						type="number" 
						id="hourly_rate"
						class="input input-bordered w-full pl-7" 
						bind:value={formData.hourly_rate}
						placeholder="0.00"
						min="0.01"
						step="0.01"
						required
					/>
				</div>
			</div>

			<!-- Active Status -->
			<div class="form-control mb-6 flex flex-row items-center gap-4">
				<label class="label w-28 shrink-0">
					<span class="label-text font-medium">Status</span>
				</label>
				<label class="label cursor-pointer justify-start gap-3 flex-1">
					<input 
						type="checkbox" 
						class="checkbox checkbox-sm" 
						bind:checked={formData.active}
					/>
					<span class="label-text">{formData.active ? 'Active' : 'Inactive'}</span>
				</label>
			</div>

			<div class="modal-action">
				<button type="button" class="btn btn-ghost" onclick={closeModal}>Cancel</button>
				<button type="submit" class="btn btn-primary" disabled={formLoading}>
					{#if formLoading}
						<span class="loading loading-spinner loading-sm"></span>
					{/if}
					{editingMember ? 'Update' : 'Create'}
				</button>
			</div>
		</form>
	</div>
	<div class="modal-backdrop" onclick={closeModal} onkeydown={(e) => e.key === 'Escape' && closeModal()} role="button" tabindex="-1"></div>
</div>
{/if}

<!-- Delete Confirmation Modal -->
{#if deleteConfirmMember}
<div class="modal modal-open">
	<div class="modal-box max-w-sm">
		<h3 class="font-bold text-lg mb-2">Confirm Delete</h3>
		<p class="text-base-content/70 mb-6">
			Are you sure you want to delete <strong>{deleteConfirmMember.name}</strong>? 
			This action cannot be undone.
		</p>

		<div class="modal-action">
			<button class="btn btn-ghost" onclick={closeDeleteModal}>Cancel</button>
			<button 
				class="btn btn-error" 
				onclick={handleConfirmDelete}
				disabled={formLoading}
			>
				{#if formLoading}
					<span class="loading loading-spinner loading-sm"></span>
				{/if}
				Delete
			</button>
		</div>
	</div>
	<div class="modal-backdrop" onclick={closeDeleteModal} onkeydown={(e) => e.key === 'Escape' && closeDeleteModal()} role="button" tabindex="-1"></div>
</div>
{/if}
