import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { CompanyRole, CompanyWithRole } from '@/types/accounting';

interface CompanyState {
  // Current active company (includes role from myCompanies query)
  activeCompany: CompanyWithRole | null;
  // List of available companies (includes role from myCompanies query)
  companies: CompanyWithRole[];
  // Loading state
  isLoading: boolean;

  // Actions
  setActiveCompany: (company: CompanyWithRole) => void;
  setCompanies: (companies: CompanyWithRole[]) => void;
  setLoading: (loading: boolean) => void;
  clearActiveCompany: () => void;
}

export const useCompanyStore = create<CompanyState>()(
  persist(
    (set) => ({
      activeCompany: null,
      companies: [],
      isLoading: false,

      setActiveCompany: (company) =>
        set({ activeCompany: company }),

      setCompanies: (companies) =>
        set({ companies }),

      setLoading: (isLoading) =>
        set({ isLoading }),

      clearActiveCompany: () =>
        set({ activeCompany: null }),
    }),
    {
      name: 'books-company-storage',
      partialize: (state) => ({
        activeCompany: state.activeCompany,
      }),
    }
  )
);

// Selector hooks for convenience
export const useActiveCompany = () =>
  useCompanyStore((state) => state.activeCompany);

export const useCompanies = () =>
  useCompanyStore((state) => state.companies);

// Get the current user's role for the active company
// Returns the role from the myCompanies query data stored on the active company
export const useActiveCompanyRole = (): CompanyRole => {
  const activeCompany = useCompanyStore((state) => state.activeCompany);
  // Return the actual role from the CompanyWithRole data, default to 'viewer' if not set
  return activeCompany?.role ?? 'viewer';
};

// Helper functions for user roles
export function getRoleLabel(role: CompanyRole): string {
  switch (role) {
    case 'owner':
      return 'Ejer';
    case 'accountant':
      return 'Bogholder';
    case 'viewer':
      return 'Læser';
    default:
      return role;
  }
}

export function getRoleColor(role: CompanyRole): string {
  switch (role) {
    case 'owner':
      return 'gold';
    case 'accountant':
      return 'blue';
    case 'viewer':
      return 'default';
    default:
      return 'default';
  }
}

// Hook to check if current user can administer the company
// Checks if the user has Owner role for the active company
export function useCanAdmin(): boolean {
  const role = useActiveCompanyRole();
  return role === 'owner';
}
