import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { Company } 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);
