import { create } from 'zustand'
import { devtools } from 'zustand/middleware'

export interface SpotlightResult {
  id: string
  type: string
  name: string
  namespace?: string
  color: string
}

export interface SpotlightState {
  open: boolean
  query: string
  filterType: string | null
  sel: number
  navigated: boolean
  results: SpotlightResult[]
  loading: boolean
  error: string | null
}

export type SpotlightFilter = 'all' | 'krate' | 'namespace' | 'pod' | 'deployment' | 'service'

interface SpotlightStore extends SpotlightState {
  setOpen: (open: boolean) => void
  setQuery: (query: string) => void
  setFilter: (filterType: SpotlightFilter | null) => void
  setSel: (sel: number) => void
  setResults: (results: SpotlightResult[]) => void
  setLoading: (loading: boolean) => void
  setError: (error: string | null) => void
  toggle: () => void
  close: () => void
}

const INITIAL_STATE: SpotlightState = {
  open: false,
  query: '',
  filterType: null,
  sel: 0,
  navigated: false,
  results: [],
  loading: false,
  error: null,
}

export const useSpotlightStore = create<SpotlightStore>()(
  devtools((set) => ({
    ...INITIAL_STATE,
    setOpen: (open: boolean) => set({ open }),
    setQuery: (query: string) => set({ query, navigated: false, sel: 0 }),
    setFilter: (filterType: SpotlightFilter | null) => set({ filterType }),
    setSel: (sel: number) => set({ sel, navigated: true }),
    setResults: (results: SpotlightResult[]) => set({ results }),
    setLoading: (loading: boolean) => set({ loading }),
    setError: (error: string | null) => set({ error }),
    toggle: () => set((state) => ({ open: !state.open })),
    close: () => set({ open: false, query: '', filterType: null, sel: 0, navigated: false, results: [], error: null }),
  }))
)
