<script lang="ts">
	import { enhance } from '$app/forms';
	import type { PageData } from './$types';

	interface Props {
		data: PageData;
	}

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

	let searchQuery = $state('');
	let isEditModalOpen = $state(false);
	let isSaving = $state(false);
	let saveMessage = $state<{ type: 'success' | 'error'; message: string } | null>(null);
	let selectedArcId = $state<string | null>(null);

	let editForm = $state<any>({
		id: '',
		name: '',
		startChapter: 1,
		endChapter: null,
		url: ''
	});

	const filteredArcs = $derived.by(() => {
		return data.arcs.filter((arc) => {
			return arc.name.toLowerCase().includes(searchQuery.toLowerCase());
		});
	});

	const openEditModal = (arc: any) => {
		selectedArcId = arc.id;
		editForm = { ...arc };
		isEditModalOpen = true;
		saveMessage = null;
	};

	const closeModal = () => {
		isEditModalOpen = false;
		selectedArcId = null;
		editForm = {
			id: '',
			name: '',
			startChapter: 1,
			endChapter: null,
			url: ''
		};
		saveMessage = null;
	};

	const handleDeleteArc = async (id: string) => {
		if (!confirm('Are you sure you want to delete this arc?')) return;

		try {
			const formData = new FormData();
			formData.append('id', id);

			const response = await fetch('?/delete', {
				method: 'POST',
				body: formData
			});

			if (response.ok) {
				window.location.reload();
			} else {
				alert('Failed to delete arc');
			}
		} catch (error) {
			alert('Error deleting arc: ' + error);
		}
	};
</script>

<svelte:head>
	<title>Arcs - Admin - OnePieceDle</title>
</svelte:head>

<div class="space-y-6">
	<!-- Header -->
	<div class="flex items-center justify-between">
		<h2 class="text-3xl font-bold text-white">Arc Management</h2>
		<button
			class="rounded-lg bg-amber-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-amber-700"
		>
			+ Add Arc
		</button>
	</div>

	<!-- Filters -->
	<div class="flex flex-col gap-4 rounded-lg border border-white/10 bg-slate-800/50 p-4 md:flex-row md:items-center">
		<input
			type="text"
			placeholder="Search arcs..."
			bind:value={searchQuery}
			class="flex-1 rounded-lg bg-slate-700 px-4 py-2 text-sm text-white placeholder-gray-400 outline-none transition focus:ring-2 focus:ring-amber-600"
		/>
	</div>

	<!-- Arcs Table -->
	<div class="rounded-lg border border-white/10">
		<div class="max-h-[calc(100vh-20rem)] overflow-auto">
			<table class="w-full">
				<thead class="sticky top-0 bg-slate-800 z-10">
					<tr class="border-b border-white/10">
					<th class="px-6 py-3 text-left text-sm font-semibold text-gray-300">Name</th>
					<th class="px-6 py-3 text-left text-sm font-semibold text-gray-300">Start Chapter</th>
					<th class="px-6 py-3 text-left text-sm font-semibold text-gray-300">End Chapter</th>
						<th class="px-6 py-3 text-left text-sm font-semibold text-gray-300">Actions</th>
					</tr>
				</thead>
				<tbody>
				{#each filteredArcs as arc}
					<tr class="border-b border-white/5 hover:bg-slate-800/50">
						<td class="px-6 py-4 text-sm text-white">{arc.name}</td>
						<td class="px-6 py-4 text-sm text-gray-400">{arc.startChapter}</td>
						<td class="px-6 py-4 text-sm text-gray-400">{arc.endChapter || '-'}</td>
						<td class="px-6 py-4 text-sm">
							<div class="flex items-center gap-2">
								<button
									onclick={() => openEditModal(arc)}
									class="text-amber-400 hover:text-amber-300 transition-colors"
									title="Edit arc"
								>
									<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path></svg>
								</button>
								<button 
									onclick={() => handleDeleteArc(arc.id)}
									class="text-red-400 hover:text-red-300 transition-colors"
									title="Delete arc"
								>
									<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
								</button>
							</div>
						</td>
					</tr>
				{/each}
				</tbody>
			</table>
		</div>	</div>
	{#if filteredArcs.length === 0}
		<div class="rounded-lg border border-white/10 bg-slate-800/50 py-12 text-center">
			<p class="text-gray-400">No arcs found</p>
		</div>
	{/if}

	<!-- Edit Modal -->
	{#if isEditModalOpen}
		<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
			<div class="w-full max-w-md rounded-lg border border-white/10 bg-slate-900 p-6">
				<h3 class="text-lg font-bold text-white">Edit Arc</h3>
				<form 
					method="POST" 
					action="?/update"
					class="mt-6 space-y-4"
					use:enhance={() => {
						isSaving = true;
						saveMessage = null;
						return async ({ result }) => {
							isSaving = false;
							if (result.type === 'success') {
								saveMessage = { type: 'success', message: 'Arc updated successfully' };
								setTimeout(() => {
									closeModal();
									window.location.reload();
								}, 500);
							} else if (result.type === 'failure') {
								saveMessage = { type: 'error', message: (result.data as any)?.error || 'Failed to update arc' };
							}
						};
					}}
				>
					<input type="hidden" name="id" value={editForm.id} />
					<div>
						<label for="arc-name" class="block text-sm font-medium text-gray-300">Name</label>
						<input
							id="arc-name"
							type="text"
							name="name"
							bind:value={editForm.name}
							class="mt-1 w-full rounded-lg bg-slate-700 px-4 py-2 text-sm text-white outline-none transition focus:ring-2 focus:ring-amber-600"
						/>
					</div>
					<div class="grid grid-cols-2 gap-4">
						<div>
							<label for="arc-start" class="block text-sm font-medium text-gray-300">Start Chapter</label>
							<input
								id="arc-start"
								type="number"
								name="startChapter"
								bind:value={editForm.startChapter}
								class="mt-1 w-full rounded-lg bg-slate-700 px-4 py-2 text-sm text-white outline-none transition focus:ring-2 focus:ring-amber-600"
							/>
						</div>
						<div>
							<label for="arc-end" class="block text-sm font-medium text-gray-300">End Chapter</label>
							<input
								id="arc-end"
								type="number"
								name="endChapter"
								bind:value={editForm.endChapter}
								class="mt-1 w-full rounded-lg bg-slate-700 px-4 py-2 text-sm text-white outline-none transition focus:ring-2 focus:ring-amber-600"
							/>
						</div>
					</div>
					<div>
						<label for="arc-url" class="block text-sm font-medium text-gray-300">URL</label>
						<input
							id="arc-url"
							type="text"
							name="url"
							bind:value={editForm.url}
							placeholder="https://..."
							class="mt-1 w-full rounded-lg bg-slate-700 px-4 py-2 text-sm text-white outline-none transition focus:ring-2 focus:ring-amber-600"
						/>
					</div>
					{#if saveMessage}
						<div class={`rounded-lg p-3 text-sm ${
							saveMessage.type === 'success' 
								? 'bg-green-500/10 text-green-400' 
								: 'bg-red-500/10 text-red-400'
						}`}>
							{saveMessage.message}
						</div>
					{/if}
					<div class="flex gap-3 pt-4">
						<button
							type="button"
							onclick={closeModal}
							disabled={isSaving}
							class="flex-1 rounded-lg border border-gray-500 px-4 py-2 text-sm font-medium text-gray-300 transition-colors hover:bg-slate-700 disabled:opacity-50"
						>
							Cancel
						</button>
						<button
							type="submit"
							disabled={isSaving}
							class="flex-1 rounded-lg bg-amber-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-amber-700 disabled:opacity-50"
						>
							{isSaving ? 'Saving...' : 'Save Changes'}
						</button>
					</div>
				</form>
			</div>
		</div>
	{/if}
</div>
