import { create } from 'zustand';
import { createJSONStorage, persist } from 'zustand/middleware';

interface User {
    id: string;
    firstName: string;
    lastName: string;
    email: string;
    userType: string;
    role?: string;
    isDentist?: boolean;
    profileImage?: string;
    ownerId?: string;
    doctor?: {
        specialization?: string;
        licenseNumber?: string;
        signatureUrl?: string;
    };
    clinic?: {
        name?: string;
        address?: string;
        phone?: string;
    };
}

interface AuthState {
    user: User | null;
    token: string | null;
    tokenExpiration: number | null;
    hasActiveSubscription: boolean;
    isLoading: boolean;

    // Actions
    setAuth: (user: User, token: string, hasActiveSubscription?: boolean) => void;
    updateUser: (user: User) => void;
    setHasActiveSubscription: (status: boolean) => void;
    logout: () => void;
    checkTokenExpiration: () => boolean;
    initializeAuth: () => void;
}

const TOKEN_DURATION = 8 * 60 * 60 * 1000; // 8 hours in milliseconds

let logoutTimer: NodeJS.Timeout | null = null;

export const useAuthStore = create<AuthState>()(
    persist(
        (set, get) => ({
            user: null,
            token: null,
            tokenExpiration: null,
            hasActiveSubscription: false,
            isLoading: true,

            setAuth: (user: User, token: string, hasActiveSubscription: boolean = false) => {
                const expiration = Date.now() + TOKEN_DURATION;

                // Clear any existing logout timer
                if (logoutTimer) {
                    clearTimeout(logoutTimer);
                }

                // Set new logout timer
                logoutTimer = setTimeout(() => {
                    get().logout();
                }, TOKEN_DURATION);

                set({
                    user,
                    token,
                    tokenExpiration: expiration,
                    hasActiveSubscription,
                    isLoading: false,
                });
            },

            updateUser: (user: User) => {
                set({ user });
            },

            setHasActiveSubscription: (status: boolean) => {
                set({ hasActiveSubscription: status });
            },

            logout: () => {
                // Clear logout timer
                if (logoutTimer) {
                    clearTimeout(logoutTimer);
                    logoutTimer = null;
                }

                set({
                    user: null,
                    token: null,
                    tokenExpiration: null,
                    hasActiveSubscription: false,
                    isLoading: false,
                });
            },

            checkTokenExpiration: () => {
                const { tokenExpiration, logout } = get();

                if (!tokenExpiration) {
                    return false;
                }

                const isExpired = Date.now() >= tokenExpiration;

                if (isExpired) {
                    logout();
                    return false;
                }

                return true;
            },

            initializeAuth: () => {
                const { token, tokenExpiration, logout, checkTokenExpiration } = get();

                if (token && tokenExpiration) {
                    // Check if token is still valid
                    const isValid = checkTokenExpiration();

                    if (isValid) {
                        // Set up logout timer for remaining time
                        const remainingTime = tokenExpiration - Date.now();

                        if (remainingTime > 0) {
                            logoutTimer = setTimeout(() => {
                                logout();
                            }, remainingTime);
                        } else {
                            logout();
                        }
                    }
                }

                set({ isLoading: false });
            },
        }),
        {
            name: 'auth-storage',
            storage: createJSONStorage(() => ({
                getItem: (name) => {
                    const str = localStorage.getItem(name);
                    if (!str) return null;

                    try {
                        const { state } = JSON.parse(str);

                        // Check token expiration on rehydration
                        if (state.tokenExpiration && Date.now() >= state.tokenExpiration) {
                            // Token expired, clear storage
                            localStorage.removeItem(name);
                            return null;
                        }

                        return str;
                    } catch {
                        return str;
                    }
                },
                setItem: (name, value) => {
                    localStorage.setItem(name, value);
                },
                removeItem: (name) => {
                    localStorage.removeItem(name);
                },
            })),
            partialize: (state) => ({
                user: state.user,
                token: state.token,
                tokenExpiration: state.tokenExpiration,
                hasActiveSubscription: state.hasActiveSubscription,
            }),
        }
    )
);

// Initialize auth on store creation (client-side only)
if (typeof window !== 'undefined') {
    useAuthStore.getState().initializeAuth();
}
