<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 filterType = $state<'all' | 'Paramecia' | 'Zoan' | 'Logia' | 'Unknown'>('all');
	let isEditModalOpen = $state(false);
	let isSaving = $state(false);
	let saveMessage = $state<{ type: 'success' | 'error'; text: string } | null>(null);

	const fruitTypes = ['Paramecia', 'Zoan', 'Logia', 'Unknown'] as const;

	let editForm = $state<any>({
		id: '',
		name: '',
		type: 'Paramecia',
		url: ''
	});

	const filteredFruits = $derived.by(() => {
		return data.devilFruits.filter((fruit) => {
			const matchesSearch = fruit.name.toLowerCase().includes(searchQuery.toLowerCase());
			const matchesFilter = filterType === 'all' || fruit.type === filterType;
			return matchesSearch && matchesFilter;
		});
	});

	const openEditModal = (fruit: any) => {
		editForm = { ...fruit };
		isEditModalOpen = true;
	};

	const closeModal = () => {
		isEditModalOpen = false;
		editForm = {
			id: '',
			name: '',
			type: 'Paramecia',
			url: ''
		};
	};

	const getTypeColor = (type: string) => {
		switch (type) {
			case 'Paramecia':
				return 'bg-blue-500/20 text-blue-300';
			case 'Zoan':
				return 'bg-green-500/20 text-green-300';
			case 'Logia':
				return 'bg-red-500/20 text-red-300';
			default:
				return 'bg-gray-500/20 text-gray-300';
		}
	};

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

		isSaving = true;
		const formData = new FormData();
		formData.append('id', id);

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

			if (response.ok) {
				location.reload();
			} else {
				const error = await response.json();
				saveMessage = {
					type: 'error',
					text: error.error || 'Failed to delete devil fruit'
				};
				setTimeout(() => {
					saveMessage = null;
				}, 3000);
			}
		} catch (error) {
			console.error('Error deleting devil fruit:', error);
			saveMessage = {
				type: 'error',
				text: 'Error deleting devil fruit'
			};
			setTimeout(() => {
				saveMessage = null;
			}, 3000);
		} finally {
			isSaving = false;
		}
	};


</script>

<svelte:head>
	<title>Devil Fruits - 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">Devil Fruit 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 Devil Fruit
		</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 devil fruits..."
			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"
		/>
		<select
			bind:value={filterType}
			class="rounded-lg bg-slate-700 px-4 py-2 text-sm text-white outline-none transition focus:ring-2 focus:ring-amber-600"
		>
			<option value="all">All Types</option>
			<option value="Paramecia">Paramecia</option>
			<option value="Zoan">Zoan</option>
			<option value="Logia">Logia</option>
			<option value="Unknown">Unknown</option>
		</select>
	</div>

	<!-- Devil Fruits 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">Type</th>
						<th class="px-6 py-3 text-left text-sm font-semibold text-gray-300">Actions</th>
					</tr>
				</thead>
				<tbody>
				{#each filteredFruits as fruit (fruit.id)}
					<tr class="border-b border-white/5 hover:bg-slate-800/50">
						<td class="px-6 py-4 text-sm text-white">{fruit.name}</td>
						<td class="px-6 py-4 text-sm">
							<span class={`inline-block rounded-full px-2 py-1 text-xs ${getTypeColor(fruit.type || 'Unknown')}`}>
								{fruit.type || 'Unknown'}
							</span>
						</td>
						<td class="px-6 py-4 text-sm">
							<div class="flex items-center gap-2">
								<button
									onclick={() => openEditModal(fruit)}
									class="text-amber-400 hover:text-amber-300 transition-colors"
									title="Edit devil fruit"
								>
									<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={() => handleDeleteFruit(fruit.id)}
									class="text-red-400 hover:text-red-300 transition-colors"
									title="Delete devil fruit"
								>
									<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 filteredFruits.length === 0}
		<div class="rounded-lg border border-white/10 bg-slate-800/50 py-12 text-center">
			<p class="text-gray-400">No devil fruits 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 Devil Fruit</h3>
				<form 
					class="mt-6 space-y-4"
					method="POST"
					action="?/update"
					use:enhance={() => {
						isSaving = true;
						return async ({ result }) => {
							isSaving = false;
							if (result.type === 'success') {
								saveMessage = { type: 'success', text: 'Devil Fruit saved successfully!' };
								setTimeout(() => {
									location.reload();
								}, 1000);
							} else if (result.type === 'failure') {
								saveMessage = { type: 'error', text: (result.data as any)?.error || 'Failed to save devil fruit' };
							}
							setTimeout(() => {
								saveMessage = null;
							}, 3000);
						};
					}}
				>
					<input type="hidden" name="id" value={editForm.id} />
					<div>
						<label for="fruit-name" class="block text-sm font-medium text-gray-300">Name</label>
						<input
							id="fruit-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>
						<label for="fruit-type" class="block text-sm font-medium text-gray-300">Type</label>
						<select
							id="fruit-type"
							name="type"
							bind:value={editForm.type}
							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"
						>
							{#each fruitTypes as type (type)}
								<option value={type}>{type}</option>
							{/each}
						</select>
					</div>
					<div>
						<label for="fruit-url" class="block text-sm font-medium text-gray-300">URL</label>
						<input
							id="fruit-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>
					<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>
				{#if saveMessage}
					<div
						class={`mt-4 rounded-lg p-3 text-sm font-medium ${
							saveMessage.type === 'success'
								? 'border border-green-500/50 bg-green-500/10 text-green-300'
								: 'border border-red-500/50 bg-red-500/10 text-red-300'
						}`}
					>
						{saveMessage.text}
					</div>
				{/if}
			</div>
		</div>
	{/if}
</div>
