<template>
    <div class="flex items-center justify-center min-h-screen bg-[#0c4b66]">
      <div class="bg-white p-8 rounded-2xl shadow-xl w-80 text-center">
        <!-- Logo + Title -->
        <div class="mb-6">
          <img :src="logo" alt="Logo" class="mx-auto w-34 py-5" />
        </div>

        <!-- Input -->
        <div>
          <InputField
            v-model="username"
            type="text"
            placeholder="Username"
            class="mb-4"
          />
          <InputPassword v-model="password" placeholder="Password" />

          <div
            v-if="errorMessage"
            class="mt-2 text-red-500 text-xs font-medium text-left"
          >
            {{ errorMessage }}
          </div>
        </div>

        <!-- Button -->
        <button
          @click="handleLogin"
          :disabled="loading"
          class="w-full mt-6 py-2 bg-sky-400 hover:bg-sky-500 rounded font-bold text-gray-800 transition disabled:opacity-50"
        >
          {{ loading ? "Loading..." : "Login" }}
        </button>
      </div>
    </div>
  </template>


<script setup>
import { ref } from "vue";
import logo from "@/../images/logo.png";
import InputField from "@/components/InputField.vue";
import InputPassword from "@/components/InputPassword.vue";
import axios from "axios";

const username = ref("");
const password = ref("");
const loading = ref(false);
const errorMessage = ref("");

const handleLogin = async () => {
    if (!username.value || !password.value) {
        errorMessage.value = "Harap isi username dan password!";
        return;
    }

    loading.value = true;
    errorMessage.value = "";
    try {
        const res = await axios.post("/api/login", {
            nama: username.value,
            password: password.value,
        });

        const data = res.data;

        // Simpan token & role
        localStorage.setItem("token", data.token);
        localStorage.setItem("role", data.role);
        localStorage.setItem("userId", data.user.id);
        localStorage.setItem("nama", data.user.nama);
        localStorage.setItem("role", data.user.role);


        // Redirect sesuai role
        window.location.href = data.redirect;
    } catch (error) {
    if (error.response?.data?.message) {
      errorMessage.value = error.response.data.message;
    } else {
      errorMessage.value = "Login gagal. Periksa username atau password.";
    }
  } finally {
    loading.value = false;
  }
};
</script>
