<script>
	import { onMount } from 'svelte';
	import { goto } from '$app/navigation';
	import { userFlag } from '$lib/utils/store';
	import beer_icon from '$lib/assets/beer_icon.svg';
	import { browser } from '$app/environment';
	import { logo_id, companyName_id } from '$lib/utils/store';

	let username = '';
	let password = '';
	let loading = false;
	let error = '';
	let data;
	let currentUser = false;
	let company;

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

	onMount(() => {
		if (currentUser) {
			goto('/dashboard/tables');
		}

		switch (company) {
			case '1':
				logo_id.set(
					'https://i.postimg.cc/bNNBcTZj/Whats-App-Image-2025-07-29-at-19-59-16-removebg-preview.png'
				);
				companyName_id.set('Bar do Ferlin');
				break;
			default:
				logo_id.set(
					'https://i.postimg.cc/7LPJk38W/beer-meal-24dp-EAC452-FILL0-wght400-GRAD0-opsz24.png'
				);
				companyName_id.set('Bar Management');
				break;
		}
	});

	function passwordForgotten() {
		goto('/forgotten');
	}

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

		if (!username || !password) {
			error = 'Por favor, preencha todos os campos';
			return;
		}

		error = '';
		loading = true;

		try {
			const response = await fetch('https://dev2.mixtech.dev.br/login', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify({
					username,
					password
				})
			});

			const result = await response.json();
			data = result;
			const token = data.data.token;
			const company = data.data.company_id;
			localStorage.setItem('token', token);
			localStorage.setItem('company', company);
			localStorage.setItem('user', username);
			if (data.status === 'ok') {
				const id = data.data.role_id;
				switch (id) {
					case 1:
						localStorage.setItem('flag', 'admin');
						break;
					case 2:
						localStorage.setItem('flag', 'waiter');
						break;
					case 3:
						localStorage.setItem('flag', 'kitchen');
						break;
					case 4:
						localStorage.setItem('flag', 'cashier');
						break;
					default:
						localStorage.setItem('flag', '');
				}
				goto('/dashboard/tables');
			} else {
				error = 'Usuário ou senha inválidos';
			}
		} catch (err) {
			console.error(err);
			error = 'Erro ao conectar com o servidor';
		} finally {
			loading = false;
		}
	}
</script>

<div class="flex min-h-screen items-center justify-center bg-[#1C1C1E] px-4">
	<div class="w-full max-w-md space-y-8 rounded-lg bg-[#2C2C2E] p-8 shadow-lg">
		<div class="flex flex-col items-center justify-center text-center">
			<img src={$logo_id} alt="" class="h-20 w-20" />
			<h1 class="mt-4 text-3xl font-extrabold text-white">{$companyName_id}</h1>
			<p class="mt-2 text-[#A0A0A0]">Login</p>
		</div>

		{#if error}
			<div class="rounded-md bg-[#FF3B30]/20 p-4 text-sm text-[#FF3B30]">
				{error}
			</div>
		{/if}

		<form class="mt-8 space-y-6" onsubmit={handleSubmit}>
			<div>
				<label for="username" class="block text-sm font-medium text-[#A0A0A0]"> Usuário </label>
				<div class="relative mt-1">
					<!-- <img src="/user-icon.svg" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-[#A0A0A0]" alt="" /> -->

					<input
						id="username"
						type="text"
						bind:value={username}
						placeholder="Digite seu usuário"
						class="block w-full rounded-md border border-[#A0A0A0]/20 bg-[#1C1C1E] py-3 pl-3 pr-3 text-white focus:border-[#D4AF37] focus:outline-none focus:ring-2 focus:ring-[#D4AF37]"
					/>
				</div>
			</div>

			<div>
				<label for="password" class="block text-sm font-medium text-[#A0A0A0]"> Senha </label>
				<div class="relative mt-1">
					<!-- <img src="/lock-icon.svg" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-[#A0A0A0]" alt="" /> -->

					<input
						id="password"
						type="password"
						bind:value={password}
						placeholder="••••••••"
						class="block w-full rounded-md border border-[#A0A0A0]/20 bg-[#1C1C1E] py-3 pl-3 pr-3 text-white focus:border-[#D4AF37] focus:outline-none focus:ring-2 focus:ring-[#D4AF37]"
					/>
				</div>
			</div>

			<div>
				<button
					type="submit"
					class="flex w-full cursor-pointer items-center justify-center rounded-md bg-[#D4AF37] px-4 py-3 text-[#1C1C1E] transition-colors hover:bg-[#D4AF37]/90 focus:outline-none focus:ring-2 focus:ring-[#D4AF37] focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
					disabled={loading}
				>
					{loading ? 'Entrando...' : 'Entrar'}
				</button>
			</div>
		</form>
		<div class="flex items-center justify-center">
			<button class="cursor-pointer text-[#D4AF37]" onclick={passwordForgotten}
				>Esqueci a senha</button
			>
		</div>
	</div>
</div>
