import { defineStore } from 'pinia';
import jwt_decode from 'jwt-decode';
import { useUiStore } from './ui';

interface UserPayload {
    id: string;
    name: string;
    email?: string;
    role?: string;
    status?: number;
    type?: number;
    company_id?: number;
    [key: string]: unknown;
}

interface DecodedToken {
    user: UserPayload;
}

export const useAuthStore = defineStore('auth', {
    state: () => ({
        resetPasswordEmail: '',
        gRecaptchaResponse: null as string | null,
        updatedFullname: localStorage.getItem('updated-fullname') || '',
        access_token: localStorage.getItem('user-token') || ''
    }),

    getters: {
        isAuthenticated: (state) => !!state.access_token,

        isSuperAdmin(): boolean {
            return this.getDecodedAccessToken.user.type === 0 || this.getDecodedAccessToken.user.type === 1;
        },

        isAdmin(): boolean {
            return this.getDecodedAccessToken.user.type === 0 || this.getDecodedAccessToken.user.type === 1 || this.getDecodedAccessToken.user.type === 2;
        },

        isCustomer(): boolean {
            return this.getDecodedAccessToken.user.type === 3;
        },

        isDestinationAccountAdmin(): boolean {
            return this.getDecodedAccessToken.user.type === 7;
        },

        getUserName(): string {
            return this.getUpdatedFullname || this.getDecodedAccessToken.user.name;
        },

        getUserId(): string {
            return this.getDecodedAccessToken.user.id;
        },

        getUserEmail(): string {
            return (this.getDecodedAccessToken.user.email as string) || '';
        },

        getCompanyId(): number {
            return (this.getDecodedAccessToken.user.company_id as number) || 0;
        },

        getAccessToken: (state) => state.access_token,

        getDecodedAccessToken: (state): DecodedToken => {
            try {
                return jwt_decode(state.access_token);
            } catch (_error) {
                return {
                    user: {
                        id: '',
                        name: '',
                        role: '',
                        status: 0
                    }
                } as DecodedToken;
            }
        },

        getResetPasswordEmail: (state) => state.resetPasswordEmail,
        getUpdatedFullname: (state) => state.updatedFullname,
        getReCaptcha: (state) => state.gRecaptchaResponse
    },

    actions: {
        userAuthentication({ access_token, redirect_url }: { access_token: string; redirect_url: string }) {
            localStorage.setItem('user-token', access_token);
            localStorage.removeItem('updated-fullname');

            this.access_token = access_token;

            const uiStore = useUiStore();
            uiStore.toggleLoading('loginSection', true);

            setTimeout(() => {
                window.location.href = redirect_url;
            }, 2000);
        },

        reCaptcha({ token }: { token: string | null }) {
            this.gRecaptchaResponse = token;
        },

        async ensureReCaptchaIsSet(): Promise<string | null> {
            return new Promise((resolve) => {
                const wait = () => {
                    if (this.gRecaptchaResponse) return resolve(this.gRecaptchaResponse);
                    setTimeout(wait, 30);
                };
                wait();
            });
        },

        updateToken({ access_token }: { access_token: string }) {
            localStorage.setItem('user-token', access_token);
            this.access_token = access_token;
        },

        passwordResetEmail({ email }: { email: string }) {
            this.resetPasswordEmail = email;
            const uiStore = useUiStore();
            uiStore.toggleLoading('forgetPasswordSection', true);
            setTimeout(() => {
                uiStore.toggleLoading('forgetPasswordSection', false);
            }, 2000);
        },

        passwordReset() {
            const uiStore = useUiStore();
            uiStore.toggleLoading('resetPasswordSection', true);
        },

        returnToLoginAfterSendResetPasswordLink() {
            const uiStore = useUiStore();
            uiStore.toggleSection('forgetPassword', false);
            uiStore.toggleSection('forgetPasswordSuccess', false);
        },

        updateProfile({ fullname }: { fullname: string }) {
            localStorage.setItem('updated-fullname', fullname);
            this.updatedFullname = fullname;
        }
    }
});
