<script>
import axios from "axios";
import Swal from "sweetalert2";
import { mapActions } from "vuex";

export default {
    data() {
        return {
            username: "",
            password: "",
            rememberMe: false,
            passwordVisible: false,
            errorMessage: "",
            isLoading: false,
        };
    },
    methods: {
        ...mapActions(["setAuthToken", "setRefreshToken", "setUser", "logout"]),
        async handleLogin() {
            this.isLoading = true;
            this.errorMessage = "";
            try {
                if (!this.username || !this.password) {
                    this.showErrorAlert("Username dan password harus diisi.");
                    this.isLoading = false;
                    return;
                }

                const response = await axios.post("/api/login", {
                    username: this.username,
                    password: this.password,
                });

                const { token, refresh_token, user } = response.data;

                if (token && refresh_token) {
                    this.handleAuthentication(token, refresh_token, user);
                    this.showSuccessAlert("Login berhasil");
                    this.$router.push({ name: "Dashboard" });
                } else {
                    this.showErrorAlert("Gagal mendapatkan token.");
                }
            } catch (error) {
                this.handleError(error);
            } finally {
                this.isLoading = false;
            }
        },
        handleAuthentication(token, refresh_token, user) {
            this.setAuthToken(token);
            this.setRefreshToken(refresh_token);
            this.setUser(user);
            this.setAxiosDefaults(token);
            this.storeSession(token, refresh_token, user);
        },
        setAxiosDefaults(token) {
            axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
        },
        storeSession(token, refresh_token, user) {
            if (this.rememberMe) {
                localStorage.setItem("authToken", token);
                localStorage.setItem("refreshToken", refresh_token);
                localStorage.setItem("user", JSON.stringify(user));
            } else {
                sessionStorage.setItem("authToken", token);
                sessionStorage.setItem("refreshToken", refresh_token);
                sessionStorage.setItem("user", JSON.stringify(user));
            }
        },
        handleError(error) {
            this.errorMessage =
                error.response?.data?.error || "Login gagal, username/password salah.";
            this.showErrorAlert(this.errorMessage);
        },
        togglePasswordVisibility() {
            this.passwordVisible = !this.passwordVisible;
        },
        showSuccessAlert(message) {
            Swal.fire({
                icon: "success",
                title: message,
                toast: true,
                position: "top-end",
                showConfirmButton: false,
                timer: 3000,
            });
        },
        showErrorAlert(message) {
            Swal.fire({
                icon: "error",
                title: message,
                toast: true,
                position: "top-end",
                showConfirmButton: false,
                timer: 3000,
            });
        },
        async refreshAuthToken() {
            try {
                const refresh_token =
                    localStorage.getItem("refreshToken") ||
                    sessionStorage.getItem("refreshToken");

                const response = await axios.post("/api/refresh-token", {
                    refresh_token,
                });

                const { token, refresh_token: new_refresh_token } = response.data;
                this.setAuthToken(token);
                this.setRefreshToken(new_refresh_token);
                this.setAxiosDefaults(token);

                if (this.rememberMe) {
                    localStorage.setItem("authToken", token);
                    localStorage.setItem("refreshToken", new_refresh_token);
                } else {
                    sessionStorage.setItem("authToken", token);
                    sessionStorage.setItem("refreshToken", new_refresh_token);
                }

                return token;
            } catch (error) {
                this.logout();
                this.$router.push({ name: "Login" });
            }
        },
        setupAxiosInterceptors() {
            axios.interceptors.response.use(
                (response) => response,
                async (error) => {
                    const { config, response } = error;
                    if (response?.status === 401 && !config._retry) {
                        config._retry = true;
                        const newToken = await this.refreshAuthToken();
                        if (newToken) {
                            config.headers["Authorization"] = `Bearer ${newToken}`;
                            return axios(config);
                        }
                    }
                    return Promise.reject(error);
                }
            );
        },
        clearSession() {
            localStorage.removeItem("authToken");
            localStorage.removeItem("refreshToken");
            localStorage.removeItem("user");
            sessionStorage.removeItem("authToken");
            sessionStorage.removeItem("refreshToken");
            sessionStorage.removeItem("user");
        },
    },
    created() {
        this.setupAxiosInterceptors();
    },
};
</script>


<template>
    <div class="page-login">
        <section>
            <div class="container container-tight">
                <div class="card card-md border-radius">
                    <div class="card-body border-radius">
                        <div class="row">
                            <div class="text-center mb-2">
                                <router-link to="/" class="navbar-brand navbar-brand-autodark">
                                    <img src="/assets/img/logo.png" height="80" alt="Logo" />
                                </router-link>
                            </div>
                            <div class="text-center">
                                <h3>
                                    CCTV STREAM <br />
                                    PLN UID KALBAR
                                </h3>
                                <h4 class="text-primary">
                                    LOGIN
                                </h4>
                            </div>
                            <hr />
                            <br />
                            <form @submit.prevent="handleLogin">
                                <div class="mb-3">
                                    <label class="form-label">Username</label>
                                    <input type="text" v-model="username" class="form-control"
                                        placeholder="Masukkan Username ..." autocomplete="off" />
                                </div>
                                <div class="mb-2">
                                    <label class="form-label">
                                        Password
                                    </label>
                                    <div class="input-group input-group-flat">
                                        <input :type="passwordVisible ? 'text' : 'password'" v-model="password"
                                            class="form-control" placeholder="Masukkan Password ..."
                                            autocomplete="off" />
                                        <span class="input-group-text">
                                            <a href="#" @click.prevent="togglePasswordVisibility" title="Lihat password"
                                                data-bs-toggle="tooltip">
                                                <i :class="passwordVisible ? 'fa fa-eye-slash' : 'fa fa-eye'"></i>
                                            </a>
                                        </span>
                                    </div>
                                </div>
                                <div class="mb-1">
                                    <label class="form-check">
                                        <input type="checkbox" v-model="rememberMe" class="form-check-input" />
                                        <span class="form-check-label">Ingat Saya</span>
                                    </label>
                                </div>
                                <div class="form-footer">
                                    <button type="submit" class="py-3 btn btn-success w-100" :disabled="isLoading">
                                        <span v-if="isLoading">
                                            <i class="fa fa-spinner fa-spin"></i>
                                            Loading...
                                        </span>
                                        <span v-else>
                                            <i class="fa fa-arrow-right me-2"></i>
                                            MASUK
                                        </span>
                                    </button>
                                </div>
                            </form>
                        </div>

                        <div class="row justify-content-center text-center mt-4">
                            <div class="col">
                                <router-link to="/" class="btn btn-link">
                                    <i class="fa fa-arrow-left me-2"></i>
                                    Kembali ke Portal
                                </router-link>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>
</template>
