<script>
	import { onMount } from 'svelte';
	import add_icon from '$lib/assets/add_icon.svg';
	import save_icon from '$lib/assets/save_icon.svg';
	import trash_icon from '$lib/assets/trash_icon.svg';
	import { browser } from '$app/environment';

	let token = null;
	let company = null;

	if (browser) {
		token = localStorage.getItem('token');
		company = Number(localStorage.getItem('company'));
	}

	let users = [];
	let isAddingUser = false;
	let newUserForm = {
		name: '',
		username: '',
		email: '',
		password: '',
		role_id: 1
	};

	function resetUserForm() {
		newUserForm = {
			name: '',
			username: '',
			email: '',
			password: '',
			role_id: 1
		};
		isAddingUser = false;
	}

	async function handleAddUser(event) {
		event.preventDefault();

		if (!newUserForm.username || !newUserForm.email || !newUserForm.password) {
			console.error('Preencha todos os campos corretamente');
			return;
		}

		const token = localStorage.getItem('token');
		const company = parseInt(localStorage.getItem('company'), 10);

		const requestOptions = {
			method: 'POST',
			headers: {
				Authorization: `Bearer ${token}`,
				'Content-Type': 'application/json'
			},
			body: JSON.stringify({
				username: newUserForm.username,
				email: newUserForm.email,
				password: newUserForm.password,
				company_id: company,
				role_id: Number(newUserForm.role_id)
			}),
			redirect: 'follow'
		};

		try {
			const response = await fetch('https://dev2.mixtech.dev.br/register', requestOptions);
			const result = await response.json();

			if (result.status === 'ok') {
				//console.log('Usuário criado com sucesso!');
				resetUserForm();
				fetchUsers();
			} else {
				console.error('Erro ao criar usuário:', result.msg || result);
			}
		} catch (error) {
			console.error('Erro de rede ao criar usuário:', error);
		}
	}

	async function handleDeleteUser(userName) {
		const token = localStorage.getItem('token');

		const myHeaders = new Headers();
		myHeaders.append('Authorization', `Bearer ${token}`);
		myHeaders.append('Content-Type', 'application/json');

		const raw = JSON.stringify({
			user_name: userName,
			company_id: company
		});

		const requestOptions = {
			method: 'POST',
			headers: myHeaders,
			body: raw,
			redirect: 'follow'
		};

		try {
			const response = await fetch('https://dev2.mixtech.dev.br/user/delete', requestOptions);
			const result = await response.json();

			if (result.status === 'ok') {
				users = users.filter((u) => u.name !== userName);
				console.log('Usuário deletado com sucesso!');
			} else {
				console.error('Erro ao deletar usuário:', result.msg || result);
			}
		} catch (error) {
			console.error('Erro na requisição de deleção:', error);
		}
	}

	function fetchUsers() {
		const token = localStorage.getItem('token');
		const company = parseInt(localStorage.getItem('company'), 10);

		fetch('https://dev2.mixtech.dev.br/user/get', {
			method: 'POST',
			headers: {
				Authorization: `Bearer ${token}`,
				'Content-Type': 'application/json'
			},
			body: JSON.stringify({ company_id: company })
		})
			.then((response) => response.json())
			.then((data) => {
				users = data.data.map((item) => ({
					id: item.user_id,
					name: item.user_name,
					email: item.user_email,
					role: item.role_id
				}));
			})
			.catch((error) => console.error('Erro ao buscar usuários:', error));
	}

	onMount(() => {
		fetchUsers();
	});
</script>

<div class="container mx-auto h-screen">
	<div class="flex flex-col">
		<div class="mb-6 flex items-center justify-between">
			<h1 class="text-2xl font-bold">Gerenciar Usuários</h1>
			<button
				on:click={() => (isAddingUser = true)}
				class="rounded-lg bg-emerald-600 p-1.5 hover:bg-emerald-700"
			>
				<img src={add_icon} alt="Adicionar" class="h-4 w-4" />
			</button>
		</div>

		<div class="overflow-hidden rounded-lg bg-gray-800 shadow-lg">
			<table class="w-full divide-y divide-gray-700">
				<thead class="bg-gray-700">
					<tr>
						<th class="px-6 py-3 text-left text-sm font-semibold text-gray-300">Username</th>
						<th class="px-6 py-3 text-left text-sm font-semibold text-gray-300">Email</th>
						<th class="px-6 py-3 text-left text-sm font-semibold text-gray-300">Cargo</th>
						<th class="px-6 py-3 text-left text-sm font-semibold text-gray-300">Ações</th>
					</tr>
				</thead>
				<tbody class="divide-y divide-gray-700">
					{#if users.length === 0}
						<tr>
							<td colspan="4" class="p-4 text-center text-gray-400">Nenhum usuário encontrado</td>
						</tr>
					{:else}
						{#each users as user}
							<tr class="hover:bg-gray-900">
								<td class="px-6 py-4 text-sm text-white">{user.name}</td>
								<td class="px-6 py-4 text-sm text-white">{user.email}</td>
								<td class="px-6 py-4 text-sm text-white"
									>{#if user.role === 1}
										Admin
									{:else if user.role === 2}
										Garçom
									{:else if user.role === 3}
										Cozinha
									{:else if user.role === 4}
										Caixa
									{/if}</td
								>
								<td class="px-6 py-4">
									<button
										on:click={() => handleDeleteUser(user.name)}
										class="rounded-lg p-1.5 text-red-400 hover:bg-red-900/20"
									>
										<img src={trash_icon} alt="Deletar" class="h-4 w-4" />
									</button>
								</td>
							</tr>
						{/each}
					{/if}
				</tbody>
			</table>
		</div>
	</div>
</div>

{#if isAddingUser}
	<div class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">
		<div class="w-full max-w-md rounded-lg bg-gray-800 p-6 shadow-lg">
			<h2 class="mb-4 text-lg font-semibold">Adicionar Novo Usuário</h2>
			<form on:submit={handleAddUser} class="space-y-4">
				<div>
					<p class="mb-1 block text-sm text-gray-400">Username</p>
					<input
						bind:value={newUserForm.username}
						class="w-full rounded-md border border-gray-600 bg-gray-700 px-3 py-2 focus:ring-emerald-500"
						placeholder="Ex: johndoe"
					/>
				</div>
				<div>
					<p class="mb-1 block text-sm text-gray-400">Email</p>
					<input
						bind:value={newUserForm.email}
						class="w-full rounded-md border border-gray-600 bg-gray-700 px-3 py-2 focus:ring-emerald-500"
						placeholder="Ex: john@example.com"
					/>
				</div>
				<div>
					<p class="mb-1 block text-sm text-gray-400">Senha</p>
					<input
						type="password"
						bind:value={newUserForm.password}
						class="w-full rounded-md border border-gray-600 bg-gray-700 px-3 py-2 focus:ring-emerald-500"
						placeholder="Digite a senha"
					/>
				</div>
				<div>
					<p class="mb-1 block text-sm text-gray-400">Tipo de Usuário</p>
					<select
						bind:value={newUserForm.role_id}
						class="w-full rounded-md border border-gray-600 bg-gray-700 px-3 py-2 text-white focus:ring-emerald-500"
					>
						<option value={1}>Admin</option>
						<option value={2}>Garçom</option>
						<option value={3}>Cozinha</option>
						<option value={4}>Caixa</option>
					</select>
				</div>
				<div class="flex space-x-2">
					<button
						type="button"
						on:click={resetUserForm}
						class="rounded-lg bg-gray-700 px-4 py-2 hover:bg-gray-600"
					>
						Cancelar
					</button>
					<button
						type="submit"
						class="flex items-center rounded-lg bg-emerald-600 px-4 py-2 hover:bg-emerald-700"
					>
						<img src={save_icon} alt="Salvar" class="mr-2 h-4 w-4" /> Salvar
					</button>
				</div>
			</form>
		</div>
	</div>
{/if}
