<template>
  <div class="login-container">
    <h2>Login</h2>
    <form @submit.prevent="handleLogin">
      <label for="username">Username:</label>
      <input id="username" v-model.trim="username" type="text" placeholder="Enter username" :class="{ 'has-error': errors.username }">
      <small v-if="errors.username">{{ errors.username }}</small>

      <label for="password">Password:</label>
      <input id="password" v-model.trim="password" type="password" placeholder="Enter password" :class="{ 'has-error': errors.password }">
      <small v-if="errors.password">{{ errors.password }}</small>

      <label><input type="checkbox" v-model="rememberMe"> Remember me</label>

      <button type="submit">Login</button>
    </form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';

const store = useStore();
const router = useRouter();

const username = ref('admin');
const password = ref('admin');
const rememberMe = ref(false);
const errors = ref({});

onMounted(() => {
  if (localStorage.getItem('rememberMe')) {
    username.value = localStorage.getItem('username');
    rememberMe.value = true;
  }
});

const handleLogin = () => {
  errors.value = {};

  if (username.value.length < 4 || username.value.length > 16 || /[^\w\s]/.test(username.value)) {
    errors.value.username = 'Username must be 4-16 characters and no special characters.';
  }

  if (password.value.length < 6 || password.value.length > 20) {
    errors.value.password = 'Password must be 6-20 characters.';
  }

  if (!errors.value.username && !errors.value.password) {
    if (username.value === 'admin' && password.value === 'admin') {
      if (rememberMe.value) {
        localStorage.setItem('username', username.value);
        localStorage.setItem('rememberMe', true);
      }
      router.push('/home');
    } else {
      errors.value.general = 'Username or password is incorrect.';
    }
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100vh;
}

.login-container label {
  margin-bottom: 0.5rem;
}

.login-container input {
  padding: 0.5rem;
  margin-bottom: 1rem;
  width: 100%;
}

.has-error {
  border-color: red;
}

.login-container button {
  padding: 0.5rem 1rem;
}
</style>
