<script lang="ts">
	import { CreateReportStore } from '$houdini';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import type { Team$result } from '$houdini';

	type TeamProfile = Team$result['teamProfiles'][number];

	interface Props {
		teamProfiles: TeamProfile[];
		onSuccess?: () => void;
		onCancel?: () => void;
	}

	let { teamProfiles, onSuccess, onCancel }: Props = $props();

	let submitting = $state(false);
	let error = $state('');

	let teamMemberId = $state('');
	let date = $state('');

	// Non-admin team members only
	let nonAdminTeamMembers = $derived(teamProfiles.filter((p) => p.role !== 'ADMIN'));

	const createStore = new CreateReportStore();

	// Format date for display (Dec 15, 2024)
	function formatDate(dateStr: string): string {
		if (!dateStr) return '';
		const d = new Date(dateStr + 'T00:00:00');
		return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
	}

	async function handleSubmit(e: SubmitEvent) {
		e.preventDefault();
		submitting = true;
		error = '';

		try {
			if (!teamMemberId || !date) {
				error = 'Please select a team member and date';
				return;
			}

			const res = await createStore.mutate({
				input: {
					teamMemberId,
					date
				}
			});

			if (res.errors?.length) {
				error = res.errors.map((e: { message: string }) => e.message).join(', ');
				return;
			}

			offCanvas.closeRight();
			onSuccess?.();
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to create report';
		} finally {
			submitting = false;
		}
	}

	function handleCancel() {
		offCanvas.closeRight();
		onCancel?.();
	}
</script>

<form onsubmit={handleSubmit} class="flex h-full flex-col">
	<div class="flex-1 space-y-6 overflow-y-auto p-6">
		<!-- Team Member -->
		<div>
			<label for="teamMember" class="mb-1.5 block text-sm font-medium text-theme">Team Member</label
			>
			<select
				id="teamMember"
				bind:value={teamMemberId}
				class="w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
				required
			>
				<option value="">Select team member...</option>
				{#each nonAdminTeamMembers as profile (profile.id)}
					<option value={profile.id}>{profile.fullName}</option>
				{/each}
			</select>
		</div>

		<!-- Date -->
		<div>
			<label for="date" class="mb-1.5 block text-sm font-medium text-theme">Report Date</label>
			<input
				type="date"
				id="date"
				bind:value={date}
				class="w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
				required
			/>
			{#if date}
				<p class="mt-1 text-sm text-theme-secondary">{formatDate(date)}</p>
			{/if}
		</div>

		<!-- Info -->
		<div class="rounded-lg bg-accent2-500/10 p-4">
			<p class="text-sm text-accent2-600 dark:text-accent2-400">
				After creating the report, you can add completed services and projects from the report
				detail page.
			</p>
		</div>

		{#if error}
			<div class="rounded-lg bg-error-500/10 p-4">
				<p class="text-sm text-error-600 dark:text-error-400">{error}</p>
			</div>
		{/if}
	</div>

	<!-- Footer -->
	<div class="flex items-center justify-end gap-3 border-t border-theme bg-theme p-6">
		<button type="button" onclick={handleCancel} class="btn-ghost" disabled={submitting}>
			Cancel
		</button>
		<button type="submit" class="btn-primary" disabled={submitting || !teamMemberId || !date}>
			{#if submitting}
				Creating...
			{:else}
				Create Report
			{/if}
		</button>
	</div>
</form>
