<script lang="ts">
	import { toast } from 'svelte-sonner';
	import * as Modal from '$lib/components/ui/dialog';
	import { Button } from '$lib/components/ui/button';
	import { apiFetch } from '$lib/utils/api';

	interface Props {
		open: boolean;
		userId: string;
		userName: string;
		onPatchTestAdded: () => void;
	}

	let { open = $bindable(), userId, userName, onPatchTestAdded }: Props = $props();

	type Service = {
		id: string;
		name: string;
		patchTestDurationHours: number;
	};

	let eligibleServices = $state<Service[]>([]);
	let selectedServiceId = $state('');
	let loading = $state(false);
	let submitting = $state(false);

	async function fetchEligibleServices() {
		if (!userId) return;
		loading = true;
		try {
			const response = await apiFetch(`/api/admin/users/${userId}/patch-tests/eligible`, {
				headers: {
					'Content-Type': 'application/json'
				}
			});

			if (response.ok) {
				eligibleServices = await response.json();
				if (eligibleServices.length > 0) {
					selectedServiceId = eligibleServices[0].id;
				}
			} else {
				const text = await response.text();
				toast.error('Failed to load services: ' + text);
			}
		} catch (err) {
			console.error('Error fetching eligible services:', err);
			toast.error('Network error loading services');
		} finally {
			loading = false;
		}
	}

	async function addPatchTest() {
		if (!selectedServiceId) {
			toast.error('Please select a service');
			return;
		}

		submitting = true;
		const loadingToast = toast.loading('Adding patch test record...');

		try {
			const response = await apiFetch(`/api/admin/users/${userId}/patch-tests`, {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify({
					service_id: selectedServiceId
				})
			});

			if (response.ok) {
				toast.success('Patch test record added successfully!', { id: loadingToast });
				open = false;
				onPatchTestAdded();
			} else {
				const text = await response.text();
				toast.error(text || 'Failed to add patch test', { id: loadingToast });
			}
		} catch (err) {
			console.error('Error adding patch test:', err);
			toast.error('Network error', { id: loadingToast });
		} finally {
			submitting = false;
		}
	}

	$effect(() => {
		if (open && userId) {
			fetchEligibleServices();
		}
	});
</script>

<Modal.Root bind:open>
	<Modal.Content class="!z-[60] sm:max-w-[425px]">
		<Modal.Header>
			<Modal.Title>Record Patch Test</Modal.Title>
		</Modal.Header>

		{#if loading}
			<div class="py-8 text-center text-gray-500">Loading available services...</div>
		{:else if eligibleServices.length === 0}
			<div class="py-8 text-center text-gray-500">
				No services require a patch test that {userName} hasn't already completed.
			</div>
		{:else}
			<div class="space-y-4 py-4">
				<div>
					<label for="service-select" class="text-sm font-medium">Select Service</label>
					<select
						id="service-select"
						bind:value={selectedServiceId}
						class="mt-1 flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-xs ring-offset-background transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50"
					>
						{#each eligibleServices as service (service.id)}
							<option value={service.id}>
								{service.name} ({service.patchTestDurationHours}h)
							</option>
						{/each}
					</select>
					<p class="mt-1 text-xs text-gray-500">
						Only services requiring a patch test that this user hasn't completed are shown.
					</p>
				</div>
			</div>
		{/if}

		<Modal.Footer>
			<Button variant="outline" onclick={() => (open = false)} disabled={submitting}>Cancel</Button>
			<Button onclick={addPatchTest} disabled={submitting || eligibleServices.length === 0}>
				{submitting ? 'Adding...' : 'Add Patch Test'}
			</Button>
		</Modal.Footer>
	</Modal.Content>
</Modal.Root>
