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

interface CompanyState {
  // Current active company
  activeCompany: Company | null;
  // List of available companies
  companies: Company[];
  // Loading state
  isLoading: boolean;

  // Actions
  setActiveCompany: (company: Company) => void;
  setCompanies: (companies: Company[]) => 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 'owner' as default for now - in production this would come from the server
export const useActiveCompanyRole = (): CompanyRole => {
  // Placeholder: In a real implementation, this would check the user's role
  // for the currently active company from the server/auth context
  return 'owner';
};

// 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
// This is a placeholder - in a real app, this would check the user's role
export function useCanAdmin(): boolean {
  // For now, return true to allow all users to manage access
  // In production, this should check the current user's role
  return true;
}
