<script lang="ts">
	import { onMount } from 'svelte';
	import { currentUser } from '$lib/stores/user';
	import { api } from '$lib/api/client';
	import { t } from '$lib/i18n';

	let loading = true;
	let error = '';
	let success = '';

	// Alliance creation
	let creatingAlliance = false;
	let newAllianceName = '';

	// Join alliance
	let joiningAlliance = false;
	let inviteCode = '';

	// Alliance details
	let allianceDetails: any = null;
	let members: any[] = [];
	let invites: any[] = [];

	// Editing
	let editingDescription = false;
	let newDescription = '';

	$: hasAlliance = $currentUser?.allianceId !== null;
	$: isOwnerOrAdmin = $currentUser?.allianceRole === 'owner' || $currentUser?.allianceRole === 'admin';

	onMount(async () => {
		await loadAllianceData();
	});

	async function loadAllianceData() {
		if (!$currentUser) return;

		loading = true;
		error = '';

		try {
			if (hasAlliance) {
				allianceDetails = await api.getAlliance();
				const membersResult = await api.getAllianceMembers(1);
				members = membersResult?.members || [];

				if (isOwnerOrAdmin) {
					const invitesResult = await api.getAllianceInvites();
					invites = invitesResult?.invites || [];
				}
			}
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to load alliance data';
		} finally {
			loading = false;
		}
	}

	async function createAlliance() {
		if (!newAllianceName.trim()) return;

		creatingAlliance = true;
		error = '';
		success = '';

		try {
			await api.createAlliance(newAllianceName.trim());
			await currentUser.fetch();
			await loadAllianceData();
			success = 'Alliance created successfully!';
			newAllianceName = '';
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to create alliance';
		} finally {
			creatingAlliance = false;
		}
	}

	async function joinAlliance() {
		if (!inviteCode.trim()) return;

		joiningAlliance = true;
		error = '';
		success = '';

		try {
			await api.joinAlliance(inviteCode.trim());
			await currentUser.fetch();
			await loadAllianceData();
			success = 'Joined alliance successfully!';
			inviteCode = '';
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to join alliance';
		} finally {
			joiningAlliance = false;
		}
	}

	async function updateDescription() {
		if (!newDescription.trim()) return;

		error = '';
		success = '';

		try {
			await api.updateAllianceDescription(newDescription.trim());
			await loadAllianceData();
			editingDescription = false;
			success = 'Description updated successfully!';
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to update description';
		}
	}

	function startEditDescription() {
		newDescription = allianceDetails?.description || '';
		editingDescription = true;
	}
</script>

<svelte:head>
	<title>Alliance - FurryPlace</title>
</svelte:head>

<div class="mx-auto max-w-6xl px-4 py-6">
	<h1 class="text-3xl font-bold mb-6">Alliance</h1>

	{#if error}
		<div class="alert alert-error mb-6">
			<span>{error}</span>
		</div>
	{/if}

	{#if success}
		<div class="alert alert-success mb-6">
			<span>{success}</span>
		</div>
	{/if}

	{#if loading}
		<div class="flex justify-center py-12">
			<span class="loading loading-spinner loading-lg"></span>
		</div>
	{:else if !hasAlliance}
		<!-- Create or Join Alliance -->
		<div class="grid gap-6 md:grid-cols-2">
			<!-- Create Alliance -->
			<div class="card bg-base-100 shadow-xl">
				<div class="card-body">
					<h2 class="card-title">Create Alliance</h2>
					<p class="text-sm text-base-content/60">
						Start your own alliance and invite other players to join you.
					</p>

					<div class="form-control mt-4">
						<label class="label" for="alliance-name">
							<span class="label-text">Alliance Name</span>
						</label>
						<input
							id="alliance-name"
							type="text"
							class="input input-bordered"
							bind:value={newAllianceName}
							placeholder="My Awesome Alliance"
							maxlength="32"
						/>
					</div>

					<div class="card-actions justify-end mt-4">
						<button
							class="btn btn-primary"
							on:click={createAlliance}
							disabled={creatingAlliance || !newAllianceName.trim()}
						>
							{creatingAlliance ? 'Creating...' : 'Create Alliance'}
						</button>
					</div>
				</div>
			</div>

			<!-- Join Alliance -->
			<div class="card bg-base-100 shadow-xl">
				<div class="card-body">
					<h2 class="card-title">Join Alliance</h2>
					<p class="text-sm text-base-content/60">
						Have an invite code? Join an existing alliance here.
					</p>

					<div class="form-control mt-4">
						<label class="label" for="invite-code">
							<span class="label-text">Invite Code</span>
						</label>
						<input
							id="invite-code"
							type="text"
							class="input input-bordered"
							bind:value={inviteCode}
							placeholder="ABC123"
							maxlength="20"
						/>
					</div>

					<div class="card-actions justify-end mt-4">
						<button
							class="btn btn-primary"
							on:click={joinAlliance}
							disabled={joiningAlliance || !inviteCode.trim()}
						>
							{joiningAlliance ? 'Joining...' : 'Join Alliance'}
						</button>
					</div>
				</div>
			</div>
		</div>
	{:else if allianceDetails}
		<!-- Alliance Management -->
		<div class="space-y-6">
			<!-- Alliance Info -->
			<div class="card bg-base-100 shadow-xl">
				<div class="card-body">
					<div class="flex justify-between items-start">
						<div>
							<h2 class="card-title text-2xl">{allianceDetails.name}</h2>
							<p class="text-sm text-base-content/60">
								{members.length} member{members.length !== 1 ? 's' : ''}
							</p>
						</div>
						<div class="text-right">
							<p class="text-xs text-base-content/50">Total Pixels</p>
							<p class="text-2xl font-bold text-primary">{allianceDetails.pixelsPainted.toLocaleString()}</p>
						</div>
					</div>

					<div class="divider"></div>

					{#if !editingDescription}
						<div>
							<div class="flex justify-between items-center mb-2">
								<p class="text-xs uppercase text-base-content/50">Description</p>
								{#if isOwnerOrAdmin}
									<button class="btn btn-ghost btn-xs" on:click={startEditDescription}>Edit</button>
								{/if}
							</div>
							<p class="text-sm">{allianceDetails.description || 'No description yet.'}</p>
						</div>
					{:else}
						<div>
							<textarea
								class="textarea textarea-bordered w-full"
								bind:value={newDescription}
								placeholder="Alliance description..."
								rows="3"
								maxlength="500"
							></textarea>
							<div class="flex gap-2 justify-end mt-2">
								<button class="btn btn-ghost btn-sm" on:click={() => (editingDescription = false)}>
									Cancel
								</button>
								<button class="btn btn-primary btn-sm" on:click={updateDescription}>
									Save
								</button>
							</div>
						</div>
					{/if}
				</div>
			</div>

			<!-- Members -->
			<div class="card bg-base-100 shadow-xl">
				<div class="card-body">
					<h3 class="card-title">Members</h3>
					<div class="overflow-x-auto">
						<table class="table table-zebra">
							<thead>
								<tr>
									<th>Name</th>
									<th>Role</th>
									<th>Pixels</th>
									{#if isOwnerOrAdmin}
										<th>Actions</th>
									{/if}
								</tr>
							</thead>
							<tbody>
								{#each members as member}
									<tr>
										<td>{member.name}</td>
										<td>
											<span class="badge" class:badge-primary={member.role === 'owner'}>
												{member.role}
											</span>
										</td>
										<td>{member.pixelsPainted?.toLocaleString() || '0'}</td>
										{#if isOwnerOrAdmin && member.id !== $currentUser?.id}
											<td>
												<button class="btn btn-ghost btn-xs">Manage</button>
											</td>
										{/if}
									</tr>
								{/each}
							</tbody>
						</table>
					</div>
				</div>
			</div>

			<!-- Invites (Owner/Admin only) -->
			{#if isOwnerOrAdmin && invites.length > 0}
				<div class="card bg-base-100 shadow-xl">
					<div class="card-body">
						<h3 class="card-title">Pending Invites</h3>
						<div class="space-y-2">
							{#each invites as invite}
								<div class="flex justify-between items-center p-3 rounded-box bg-base-200">
									<div>
										<p class="font-medium">Code: {invite.code}</p>
										<p class="text-xs text-base-content/60">
											Created {new Date(invite.createdAt).toLocaleDateString()}
										</p>
									</div>
								</div>
							{/each}
						</div>
					</div>
				</div>
			{/if}
		</div>
	{/if}
</div>
