import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";
import AsyncStorage from "@react-native-async-storage/async-storage";

export type UserRole =
  | "ADMIN"
  | "BUSINESS_OWNER"
  | "EMPLOYEE"
  | "ACCOUNTANT"
  | "CUSTOMER_SERVICE"
  | "AUDITOR"
  | "VIEWER";

export interface User {
  id: string;
  email: string;
  firstName: string;
  lastName: string;
  phone: string;
  role: UserRole;
  avatar?: string;
}

interface AuthState {
  user: User | null;
  token: string | null;
  refreshToken: string | null;
  permissions: string[];
  isAuthenticated: boolean;
  setAuth: (
    user: User,
    token: string,
    refreshToken?: string,
    permissions?: string[],
  ) => void;
  setTokens: (token: string, refreshToken?: string) => void;
  logout: () => Promise<void>;
  updateUser: (user: Partial<User>) => void;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      user: null,
      token: null,
      refreshToken: null,
      permissions: [],
      isAuthenticated: false,
      setAuth: (user, token, refreshToken = undefined, permissions = []) => {
        const state = get();
        console.log("[AuthStore] Setting auth state:", {
          hasUser: !!user,
          hasToken: !!token,
          hasRefreshToken: !!refreshToken,
          permissionsCount: permissions?.length || 0,
        });
        set({
          user,
          token,
          refreshToken: refreshToken ?? state.refreshToken,
          permissions:
            permissions && permissions.length > 0
              ? permissions
              : state.permissions,
          isAuthenticated: true,
        });
      },
      setTokens: (token, refreshToken) => {
        console.log("[AuthStore] Updating tokens surgically:", {
          hasToken: !!token,
          hasRefreshToken: !!refreshToken,
        });
        set((state) => ({
          token,
          refreshToken: refreshToken ?? state.refreshToken,
          isAuthenticated: true,
        }));
      },
      logout: async () => {
        console.log("[AuthStore] Logging out...");
        const { isAuthenticated, token } = get();

        if (isAuthenticated && token) {
          try {
            // Use require to avoid circularity and module flag errors
            const { api } = require("./api");
            await api.auth.logout();
            console.log("[AuthStore] Server-side logout success.");
          } catch (e: any) {
            console.warn("[AuthStore] Server-side logout failed:", e.message);
          }
        }

        set({
          user: null,
          token: null,
          refreshToken: null,
          permissions: [],
          isAuthenticated: false,
        });
      },
      updateUser: (updatedUser) =>
        set((state) => {
          console.log("[AuthStore] Updating user profile.");
          return {
            user: state.user ? { ...state.user, ...updatedUser } : null,
          };
        }),
    }),
    {
      name: "yaltopia-auth-storage",
      storage: createJSONStorage(() => AsyncStorage),
    },
  ),
);
