"use client"

import { create } from "zustand"
import { persist } from "zustand/middleware"
import {
  DEFAULT_ACCOUNT_ID,
  MOCK_USER_ACCOUNTS,
} from "@/lib/accounts/mock-accounts"
import type { UserAccount } from "@/lib/accounts/types"
import { debouncedPersistJSONStorage } from "@/lib/stores/debounced-json-storage"

type AccountStoreState = {
  activeAccountId: string
  otherAccountsExpanded: boolean
}

type AccountStoreActions = {
  setActiveAccount: (id: string) => void
  setOtherAccountsExpanded: (expanded: boolean) => void
  toggleOtherAccountsExpanded: () => void
  signOutAll: () => void
}

export function getAccountById(id: string): UserAccount | undefined {
  return MOCK_USER_ACCOUNTS.find((a) => a.id === id)
}

export function useActiveAccount(): UserAccount {
  const activeAccountId = useAccountStore((s) => s.activeAccountId)
  return getAccountById(activeAccountId) ?? MOCK_USER_ACCOUNTS[0]!
}

export const useAccountStore = create<AccountStoreState & AccountStoreActions>()(
  persist(
    (set) => ({
      activeAccountId: DEFAULT_ACCOUNT_ID,
      otherAccountsExpanded: true,

      setActiveAccount: (id) => set({ activeAccountId: id }),

      setOtherAccountsExpanded: (expanded) =>
        set({ otherAccountsExpanded: expanded }),

      toggleOtherAccountsExpanded: () =>
        set((s) => ({ otherAccountsExpanded: !s.otherAccountsExpanded })),

      signOutAll: () =>
        set({ activeAccountId: DEFAULT_ACCOUNT_ID, otherAccountsExpanded: true }),
    }),
    {
      name: "ultimail-accounts",
      storage: debouncedPersistJSONStorage,
      partialize: (s) => ({
        activeAccountId: s.activeAccountId,
        otherAccountsExpanded: s.otherAccountsExpanded,
      }),
    },
  ),
)
