<script lang="ts">
	import * as Card from '$lib/components/ui/card/index.js';
	import { Button } from '$lib/components/ui/button/index.js';
	import { Separator } from '$lib/components/ui/separator/index.js';
	import { toast } from 'svelte-sonner';
	import { authStore } from '$lib/stores/auth.svelte';

	type Service = {
		id: string;
		name: string;
		description: string;
		price: number;
		duration_minutes: number;
		patch_test_duration_hours: number;
		minimum_age_required: number;
	};

	let services = $state<Service[]>([]);
	let servicesLoading = $state(true);

	// Fetch active services for the price list
	async function fetchServices() {
		servicesLoading = true;
		try {
			const response = await fetch('/api/services', {
				method: 'GET',
				headers: {
					'Content-Type': 'application/json',
					Authorization: `Bearer ${authStore.currentToken}`
				}
			});

			if (response.ok) {
				const data: Service[] = await response.json();
				services = data;
			} else {
				console.error('Failed to fetch services:', response.status);
				toast.error('Failed to load services');
				// Fallback to empty array
				services = [];
			}
		} catch (err) {
			console.error('Error fetching services:', err);
			toast.error('Network error loading services');
			// Fallback to empty array
			services = [];
		} finally {
			servicesLoading = false;
		}
	}

	// Format duration from minutes to human readable
	function formatDuration(minutes: number): string {
		const hours = Math.floor(minutes / 60);
		const remainingMinutes = minutes % 60;

		if (hours === 0) {
			return `${remainingMinutes} minutes`;
		} else if (remainingMinutes === 0) {
			return `${hours} ${hours === 1 ? 'hour' : 'hours'}`;
		} else {
			return `${hours} ${hours === 1 ? 'hour' : 'hours'} ${remainingMinutes} minutes`;
		}
	}

	// Format price as currency
	function formatPrice(price: number): string {
		return `£${price.toFixed(2)}`;
	}

	// Initialize on component mount
	$effect(() => {
		fetchServices();
	});
</script>

<div class="mx-auto max-w-4xl p-4 sm:p-6">
	<div class="mb-6 text-center sm:mb-8">
		<h1 class="mb-2 text-2xl font-bold sm:text-3xl">Our Prices</h1>
		<p class="text-gray-600">Professional beauty treatments with transparent pricing</p>
	</div>

	{#if servicesLoading}
		<div class="flex justify-center py-12">
			<div class="text-center">
				<div class="mb-4 text-lg text-gray-600">Loading services...</div>
				<div
					class="border-primary inline-block h-8 w-8 animate-spin rounded-full border-4 border-solid border-r-transparent align-[-0.125em] motion-reduce:animate-[spin_1.5s_linear_infinite]"
				></div>
			</div>
		</div>
	{:else if services.length === 0}
		<div class="py-12 text-center">
			<div class="mb-4 text-lg text-gray-600">No services available at the moment.</div>
			<Button href="/contact" variant="outline">Contact Us</Button>
		</div>
	{:else}
		<div class="space-y-4">
			{#each services as service, index}
				<!-- Service item layout -->
				<div
					class="border-muted/40 bg-secondary/50 hover:bg-secondary/80 rounded-lg border p-4 transition-colors"
				>
					<div class="flex items-start justify-between">
						<div class="min-w-0 flex-1">
							<h4 class="text-foreground font-semibold">{service.name}</h4>
							<p class="text-muted-foreground mt-1 text-sm">{service.description}</p>
							<!-- Duration shown on mobile -->
							<p class="text-muted-foreground mt-2 text-sm sm:hidden">
								<span class="inline-flex items-center">
									<svg class="text-primary/70 mr-1 h-3 w-3" fill="currentColor" viewBox="0 0 20 20">
										<path
											fill-rule="evenodd"
											d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-13a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V5z"
											clip-rule="evenodd"
										/>
									</svg>
									{formatDuration(service.duration_minutes)}
								</span>
							</p>
							{#if service.patch_test_duration_hours > 0}
								<p class="mt-1 text-xs text-amber-600">
									Patch test required {service.patch_test_duration_hours}h before appointment
								</p>
							{/if}
							{#if service.minimum_age_required > 0}
								<p class="mt-1 text-xs text-blue-600">
									Minimum age: {service.minimum_age_required} years
								</p>
							{/if}
						</div>
						<div class="ml-4 text-right">
							<!-- Price always visible -->
							<div class="text-primary text-lg font-semibold">{formatPrice(service.price)}</div>
							<!-- Duration shown on desktop -->
							<div class="text-muted-foreground hidden text-sm sm:block">
								{formatDuration(service.duration_minutes)}
							</div>
						</div>
					</div>
				</div>

				<!-- Separator between services (except last one) -->
				{#if index < services.length - 1}
					<Separator class="bg-muted/60" />
				{/if}
			{/each}
		</div>

		<!-- Important Information -->
		<Card.Root
			class="mt-6 border-amber-200/60 bg-gradient-to-r from-amber-50 to-amber-100/50 sm:mt-8"
		>
			<Card.Content class="pt-4 sm:pt-6">
				<div class="space-y-2 text-sm text-amber-900">
					<h4 class="font-semibold text-amber-800">Important Information:</h4>
					<ul class="space-y-1 pl-4">
						<li>
							• Prices and durations are estimates and may vary based on individual requirements
						</li>
						<li>• Patch tests are required 24-48 hours before certain treatments</li>
						<li>• 24 hours notice required for cancellations</li>
						<li>• Payment is due at the time of service</li>
						<li>• Deposit required for new and guest accounts</li>
					</ul>
				</div>
			</Card.Content>
		</Card.Root>

		<!-- Call to Action -->
		<div
			class="from-primary/5 to-secondary/30 mt-6 rounded-xl bg-gradient-to-br p-6 text-center sm:mt-8 sm:p-8"
		>
			<h2 class="text-primary mb-4 text-lg font-semibold sm:text-xl">Ready to Book?</h2>
			<div class="flex flex-col gap-3 sm:flex-row sm:justify-center sm:gap-4">
				<Button href="/book" class="px-6 py-3 sm:px-8">Book Appointment</Button>
				<Button
					href="/contact"
					variant="outline"
					class="border-primary/30 hover:bg-primary/10 px-6 py-3 sm:px-8"
				>
					Get in Touch
				</Button>
			</div>
		</div>
	{/if}
</div>
