'use client'

import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import { useQueryClient } from '@tanstack/react-query'
import { useAuthStore, AUTH_STORAGE_KEY, LEGACY_AUTH_KEYS } from '@/lib/api/auth-store'
import { useMailAccounts } from '@/lib/api/hooks/use-mail-queries'
import { debouncedPersistJSONStorage } from '@/lib/stores/debounced-json-storage'
import type { ApiMailAccount } from '@/lib/api/types'

type AccountStoreState = {
  activeAccountId: string | null
  otherAccountsExpanded: boolean
}

type AccountStoreActions = {
  setActiveAccountId: (id: string | null) => void
  setOtherAccountsExpanded: (expanded: boolean) => void
  toggleOtherAccountsExpanded: () => void
}

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

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

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

      toggleOtherAccountsExpanded: () =>
        set((s) => ({ otherAccountsExpanded: !s.otherAccountsExpanded })),
    }),
    {
      name: 'ultimail-accounts',
      storage: debouncedPersistJSONStorage,
      partialize: (s) => ({
        activeAccountId: s.activeAccountId,
        otherAccountsExpanded: s.otherAccountsExpanded,
      }),
    },
  ),
)

export function useActiveAccount(): ApiMailAccount | null {
  const activeAccountId = useAccountStore((s) => s.activeAccountId)
  const { data: accounts } = useMailAccounts()
  return accounts?.find((a) => a.id === activeAccountId) ?? accounts?.[0] ?? null
}

export function useSignOutAll() {
  const queryClient = useQueryClient()

  return async () => {
    await fetch("/api/auth/logout", { method: "POST", credentials: "include" })
    if (typeof window !== "undefined") {
      localStorage.removeItem(AUTH_STORAGE_KEY)
      for (const legacy of LEGACY_AUTH_KEYS) {
        localStorage.removeItem(legacy)
      }
    }
    useAuthStore.getState().logout()
    queryClient.clear()
    useAccountStore.setState({ activeAccountId: null, otherAccountsExpanded: true })
    window.location.href = "/login"
  }
}
